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

Shipra Swati picture Shipra Swati · Aug 31, 2014 · Viewed 326k times · Source

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

{
    "_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),
    "name" : "Swati",
    "roll" : "80",
}

I want to retrieve the field roll only for all 10 records in the collection as we would do in traditional database by using:

SELECT roll FROM student

I went through many blogs but all are resulting in a query which must have WHERE clause in it, for example:

db.students.find({ "roll": { $gt: 70 })

The query is equivalent to:

SELECT * FROM student WHERE roll > 70

My requirement is to find a single key only without any condition. So, what is the query operation for that.

Answer

therealrootuser picture therealrootuser · Aug 31, 2014

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.