Skip to content

How to return only specific fields from a MongoDB query?

In this post let’s discuss how to get only specific fields from a MongoDB query. By default, queries in MongoDB return all fields in matching documents. To restrict fields we can pass a projection document to your find query.

Syntax

db.collection.find( filter, [projection] )

projection is an optional document that restricts the fields returned from a MongoDB query.

Advertisements

Usage and examples

For example, if you want to return only the username from users collection, projection document would look like:

db.users.find({}, {username: 1} )

This would actually fetch all documents in user collection but it would return the username only.

[{username: "James"}, {username:"Naveen"}]

You can add filters like:

db.users.find({status: "active"}, {username: 1} )

If you want to return all fields but skip only a few fields, you can send 0 for the field in the projection document. For eg, if you want to skip the _id field:

db.users.find( {status: "active"}, {_id: 0} )

In the case of embedded documents, you can send the projection document with the inner key of the embedded document. For example, if address is an embedded document and you want return only the zip code, the query would look like:

db.users.find({status: "active"}, {username: 1, "address.zip": 1} )

node.js implementation

In node.js’ native mongo driver, you have to send the projection document like the below to make it work.

db.users.find( {status: "active"}, {projection: {username:1,_id: 0}} )
, , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.