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 thenameandagefields from the collection.{}: This is an empty document that specifies that all documents in the collection should be selected.name: 1: This specifies that thenamefield should be included in the query.age: 1: This specifies that theagefield should be included in the query.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to use triggers in MongoDB?
- How to update many documents in MongoDB?
- How to use MongoDB query with "or" condition?
- How to check the version of MongoDB?
- How to use unwind in MongoDB?
- How to implement pagination in MongoDB?
- How to use hint in MongoDB?
- How to do text search in MongoDB?
- How to use transactions in MongoDB?
See more codes...