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 use triggers in MongoDB?
- How to update many documents in MongoDB?
- How to use eq in MongoDB?
- How to create a many to many relation in MongoDB?
- How to use MongoDB queue?
- How to set MongoDB oplog?
- How to do joins in MongoDB?
- How to insert many docs in MongoDB?
See more codes...