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 check the version of MongoDB?
- How to use watch in MongoDB?
- How to update one document in MongoDB?
- How to update many documents in MongoDB?
- How to use MongoDB queue?
- How to create a many to many relation in MongoDB?
- How to insert new document into MongoDB?
- How to use hint in MongoDB?
- How to work with time series data in MongoDB?
- How to use unwind in MongoDB?
See more codes...