Advertisements

How to Query in MongoDB?

Advertisements

MongoDB is an open source NoSQL database. It stores or retrieve data in the form of JSON-like documents. Just like Mysql where we can select records with specific conditions, ordering records, grouping records, limiting records, using Math functions etc. Similarly, In mongodb we can find records with conditions, limiting records etc. In this tutorial we will learn how to query in MongoDB.

Mongodb Like Query to Return Documents

db.users.find({“name”: /.m./})

This will return documents where name contains ‘m’.


Mongodb Where Condition

db.users.find( { age: { $gt: 12 } } )

This will return documents where age greater than 12.

db.users.find( { _id: 5 } )

This will return documents where id is 5.

db.users.find( { birth: { $gt: new Date(‘1940-01-01’), $lt: new Date(‘1960-01-01’) } } )

This operation returns from the documents where birth is between new Date(‘1940-01-01’) and new Date(‘1960-01-01’).


Mongodb Multiple Where Conditions

db.users.find( {
birth: { $gt: new Date(‘1920-01-01’) },
death: { $exists: false }
} )

This operation returns all the documents where birth field is greater than new Date(‘1950-01-01’) and death field does not exists.


Mongodb Query an Array of Documents

db. users.find(
{ awards: { $elemMatch: { award: “Turing Award”, year: { $gt: 1980 } } } }
)

This operation returns documents where the awards array contains at least one element with both the award field equals “Turing Award” and the year field greater than 1980.


Specify the Fields to Return in Mongodb

db.users.find( { }, { name: 1, contribs: 1 } )

This operation finds all documents and returns only the name field, contribs field and _id field.


Limit the Number of Documents to Return in Mongodb

db.users.find().limit( 5 )

This will return only 5 documents.


Offset in Mongodb

db.users.find().skip( 5 )

This will skip or offset 5 documents from start.


Count in Mongodb

db.users.find().count()

This will count the documents.


Order by in Mongodb

db.users.find().sort( { name: 1 } )

This operation returns documents sorted in ascending order by the name field.


These are the basic mongodb queries you can use in your project. In detail you can about mongodb query here.


Recommendation

Using MongoDB in Node.js

How to validate form in ReactJS

How to create charts in ReactJS

For more Mongodb Tutorials Click hereNode.js Tutorials Click here.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube.

Comments are closed.