mongodb find specific fields code example

Example 1: mongodb find field based on variable

var name = req.params.name;
var value = req.params.value;
var query = {};
query[name] = value;
collection.findOne(query, function (err, item) { ... });

Example 2: mongodb select specific fields

db.student.find({}, 'roll _id'); // <--- Just multiple fields name space separated
// OR
db.student.find({}).select('roll _id'); // <--- Just multiple fields name space separated
// OR
db.student.find({}, {'roll' : 1 , '_id' : 1 ); // <---- Old lengthy boring way

Example 3: mongodb select fields

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

Example 4: find only one field mongodb

db.students.find({}, {roll:1, _id:0})

Tags:

Misc Example