MongoDB

MONGODB: What is a projection?

Posted on Updated on

A projection is when you search for documents in MongoDB but only get back the fields that you request.

example records ¬† {name: “Tom”, age: “35”, zipcode: “10003”,_id:778789754}

using projection for name and zipcode: {name: “Tom”, ¬†zipcode: “10003”}

 

var mongo = require(“mongodb”).MongoClient;
var url = “mongodb://localhost/addressbook”;
var collectionName = “friends”;
mongo.connect(url,function(err,db){
if(err) console.log(err)//throw err;
else{
var collection = db.collection(collectionName);
collection.find({},{name: 1, age: 0,_id:0,zipcode: 0}).toArray( function(err,documents){
if(err) console.log(err)//throw err;
else{
console.log(documents)
}
});

db.close();
}
})