How do I describe a collection in Mongo?

前端 未结 12 601
终归单人心
终归单人心 2021-01-31 02:32

So this is Day 3 of learning Mongo Db. I\'m coming from the MySql universe...

A lot of times when I need to write a query for a MySql table I\'m unfamiliar with, I woul

12条回答
  •  孤街浪徒
    2021-01-31 02:39

    AFAIK, there isn't a way and it is logical for it to be so.

    MongoDB being schema-less allows a single collection to have a documents with different fields. So there can't really be a description of a collection, like the description of a table in the relational databases.

    Though this is the case, most applications do maintain a schema for their collections and as said by Chris this is enforced by your application.

    As such you wouldn't have to worry about first fetching the available keys to make a query. You can just ask MongoDB for any set of keys (i.e the projection part of the query) or query on any set of keys. In both cases if the keys specified exist on a document they are used, otherwise they aren't. You will not get any error.

    For instance (On the mongo shell) :

    If this is a sample document in your people collection and all documents follow the same schema:

    {
      name : "My Name"
      place : "My Place"
      city : "My City"
    }
    

    The following are perfectly valid queries :

    These two will return the above document :

    db.people.find({name : "My Name"})
    db.people.find({name : "My Name"}, {name : 1, place :1})
    

    This will not return anything, but will not raise an error either :

    db.people.find({first_name : "My Name"})
    

    This will match the above document, but you will have only the default "_id" property on the returned document.

    db.people.find({name : "My Name"}, {first_name : 1, location :1})
    

提交回复
热议问题