MongoDB

Query Documents using Mongo Shell

The db.collection.find() method retrieves all documents from a collection.

 > db.users.find()  
{ "_id" : ObjectId("55236e5d82bf196454a94ece"), "name" : "yIIhato", "email" : "QJFDIhwi@VdQdJrvRa.com" }
{ "_id" : ObjectId("55236e5d82bf196454a94ecf"), "name" : "BejpPVb", "email" : "rXhenUnL@gIiEMTwZv.com" }
{ "_id" : ObjectId("55236e5d82bf196454a94ed0"), "name" : "jAXiuug", "email" : "hqChGtpS@MxnAHNIai.com" }

Specify Equality Condition
To specify equality condition, use the query document { : } to select all documents. The following example retrieves from the users collection all documents where the name field has the value “Himen Patel”.

 >db.users.find({Name : "Himen Patel"})  
{ "_id" : ObjectId("56130d23ba30465f56b57448"), "Name" : "Himen Patel", "Email" : "email2himen@xxx.com", "Address1" : "5619 Loyola", "City" : "Columbus", "Zip Code" : "43221", "Country" : "USA" }


Specify Conditions Using Query Operators
A query document can use the query operators to specify conditions in a MongoDB query. The following example selects all documents in the users collection where the value of the name field is either ‘Himen Patel’ or ‘Hiren Patel’.

 > db.users.find( { Name : { $in: [ 'Himen Patel', 'Hiren Patel' ] } } )  
{ "_id" : ObjectId("56130d23ba30465f56b57448"), "Name" : "Himen Patel", "Email" : "email2himen@xxx.com", "Address1" : "5619 Loyola", "City" : "Columbus", "Zip Code" : "43221", "Country" : "USA" }
{ "_id" : ObjectId("561318adba30465f56b57449"), "Name" : "Hiren Patel", "Email" : "email2hiren@xxx.com", "Address1" : "131 Beacon Ave", "City" : "Jersey City", "Zip Code" : "07306", "Country" : "USA" }

Specify AND Conditions

 > db.users.find( { Name: 'Himen Patel', Email: 'email2himen@xxx.com' } )  
{ "_id" : ObjectId("56130d23ba30465f56b57448"), "Name" : "Himen Patel", "Email" : "email2himen@xxx.com", "Address1" : "5619 Loyola", "City" : "Columbus", "Zip Code" : "43221", "Country" : "USA" }

Specify OR Conditions

 > db.users.find(  
... {
... $or: [ { Name : "Himen Patel" }, { Name : "Hiren Patel"} ]
... }
... )
{ "_id" : ObjectId("56130d23ba30465f56b57448"), "Name" : "Himen Patel", "Email" : "email2himen@xxx.com", "Address1" : "5619 Loyola", "City" : "Columbus", "Zip Code" : "43221", "Country" : "USA" }
{ "_id" : ObjectId("561318adba30465f56b57449"), "Name" : "Hiren Patel", "Email" : "email2hiren@xxx.com", "Address1" : "131 Beacon Ave", "City" : "Jersey City", "Zip Code" : "07306", "Country" : "USA" }
>

Leave a comment