mongodbHow to select specific fields in MongoDB query?
MongoDB provides the $project
operator to select specific fields in a query. The $project
operator takes a document that specifies the fields to include or exclude.
Example
db.collection.find({}, {name: 1, age: 1})
Output example
{ "_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"), "name" : "John", "age" : 25 }
The code above will select the name
and age
fields from the collection.
Code explanation
db.collection.find({}, {name: 1, age: 1})
: This is the MongoDB query that will select thename
andage
fields from the collection.{}
: This is an empty document that specifies that all documents in the collection should be selected.name: 1
: This specifies that thename
field should be included in the query.age: 1
: This specifies that theage
field should be included in the query.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to check the version of MongoDB?
- How to perform a health check for MongoDB?
- How to use eq in MongoDB?
- How to use hint in MongoDB?
- How to empty an array in MongoDB?
- How to update an array element in MongoDB?
- How to list MongoDB users?
- How to use Docker Compose with MongoDB?
- How to create a many to many relation in MongoDB?
See more codes...