How to select a single field for all documents in a MongoDB collection?

前端 未结 20 1713
执念已碎
执念已碎 2020-11-22 07:58

In my MongoDB, I have a student collection with 10 records having fields name and roll. One record of this collection is:

{
    \"         


        
20条回答
  •  忘掉有多难
    2020-11-22 08:44

    From the MongoDB docs:

    A projection can explicitly include several fields. In the following operation, find() method returns all documents that match the query. In the result set, only the item and qty fields and, by default, the _id field return in the matching documents.

    db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

    In this example from the folks at Mongo, the returned documents will contain only the fields of item, qty, and _id.


    Thus, you should be able to issue a statement such as:

    db.student.find({}, {roll:1, _id:0})
    

    The above statement will select all documents in the students collection, and the returned document will return only the roll field (and exclude the _id).

    If we don't mention _id:0 the fields returned will be roll and _id. The '_id' field is always displayed by default. So we need to explicitly mention _id:0 along with roll.

提交回复
热议问题