Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

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 the 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?

1 Answer

0 votes
by (106k points)

To select a single field for all documents in a MongoDB collection 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 } )

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...