Projection in MongoDB

In MongoDB, projection means selecting only the necessary data rather than 

selecting the whole of the data of a document. If a document has 5 fields and 

you need to show only 3, then select only 3 fields from them.

You may also like MongoDb insert.

1)Projection in find.

Here 0 means not to project i.e exclusion and 1 means project i.e inclusion as per MongoDB.

Projection cannot have a mix of inclusion and exclusion but only the _id field can exclude with inclusion.

db.collection("companies").find({name:"Dvara SmartGold"},{projection: { _id:0,id: 1, name: 1 } }).toArray()


db.collection("companies").find({name:"Dvara SmartGold"}).project({_id:0,id: 1, name: 1}).toArray()

This will give us all documents inside companies collection as per filter with only name and id fields.

2)Projection in findOne.

db.collection("companies").findOne({name:"Dvara SmartGold"},{projection: { _id:0,id: 1, name: 1 } })

//This will give us one document inside companies collection as per filter with only name and id fields.

3)Projection in Arregation.



        $match: { 'name': 'Dvara SmartGold' },



        $lookup: {

            from: "partners",

            localField: "id",

            foreignField: "refid",

            as: "partner"




        $project: {

            id: 1,

            name: 1,

            partner: 1




This will give us documents inside companies collection and also we have join partners collection as per filter with only name, partner, and id fields.


Popular posts from this blog

Node JS:Understanding bin in package.json.

Node.js: create an excel file with multiple tabs.

Node.js: Downloading a xml file from given url and reading its data elements.