MongoDB Query Document - MongoDB

How to query document from MongoDB collection?

In this chapter, we will explain how to query document from MongoDB collection.

find() Method

To query data from MongoDB collection, you can use MongoDB's find() method.

Syntax

Basic syntax of find() method is as follows

find() method displays all the documents in a non-structured way.

pretty() Method

To display the results in a formatted way, pretty() method can be used.

Syntax

Example

Apart from find() method, findOne() method also returns a single document.

RDBMS Where Clause Equivalents in MongoDB

To query the document on the basis of some condition, you can use below operations.

Operation

Syntax

Example

RDBMS Equivalent

Equality

{<key>:<value>}

db.mycol.find({"by":"wisdomjobs"}).pretty()

where by = 'wisdomjobs'

Less Than

{<key>:{$lt:<value>}}

db.mycol.find({"likes":{$lt:50}}).pretty()

where likes < 50

Less Than Equals

{<key>:{$lte:<value>}}

db.mycol.find({"likes":{$lte:50}}).pretty()

where likes <= 50

Greater Than

{<key>:{$gt:<value>}}

db.mycol.find({"likes":{$gt:50}}).pretty()

where likes > 50

Greater Than Equals

{<key>:{$gte:<value>}}

db.mycol.find({"likes":{$gte:50}}).pretty()

where likes >= 50

Not Equals

{<key>:{$ne:<value>}}

db.mycol.find({"likes":{$ne:50}}).pretty()

where likes != 50

AND in MongoDB

Syntax

In the find() method, multiple keys can be passed by separating them by with ','. MongoDB treats this symbol as AND condition. Below is the basic syntax of AND

Example

Below example shows all the tutorials written by ‘wisdomjobs’ and whose title is 'MongoDB Overview'.

For the above given example, equivalent where clause will be ' where by = 'wisdomjobs' AND title = 'MongoDB Overview' '. Any number of keys can be passed as value pairs in find clause.

OR in MongoDB

Syntax

To query documents based on the OR condition, you can use $or keyword. Below is the basic syntax of OR

Example

Below example shows all the tutorials written by 'wisdomjobs' or whose title is 'MongoDB Overview'.

Using AND and OR Together

Example

Below example shows the documents which have likes greater than 10 and whose title is either 'MongoDB Overview' or by is 'wisdomjobs'. Equivalent SQL where clause is 'where likes>10 AND (by = 'wisdomjobs' OR title = 'MongoDB Overview')'

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics