Querying MongoDB is easy
2 min readApr 27, 2020
Hope you always enjoy working with NoSQL or the document database like MongoDB. It’s very easy to use and explore.
To make it easier, below is the snippet of the most frequently used queries in MongoDB.
Sample :
{ "_id": "apples", "qty": 5 }
{ "_id": "bananas", "qty": 7 }
{ "_id": "oranges", "qty": { "in stock": 8, "ordered": 12 } }
{ "_id": "avocados", "qty": "fourteen" }db.collection.find( { qty: { $gt: 4 } } )
Result :
{ “_id”: “apples”, “qty”: 5 }
{ “_id”: “bananas”, “qty”: 7 }
{
"_id" : <value>,
"name" : { "first" : <string>, "last" : <string> }, // embedded document
"birth" : <ISODate>,
"death" : <ISODate>,
"contribs" : [ <string>, ... ], // Array of Strings
"awards" : [
{ "award" : <string>, year: <number>, by: <string> } // Array of embedded documents
...
]
}db.bios.find() # Find Alldb.bios.find( { _id: 5 } )db.bios.find( { "name.last": "Hopper" } )db.bios.find(
{ _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } }
)
db.bios.find( { birth: { $gt: new Date(‘1950–01–01’) } } )
db.bios.find(
{ "name.last": { $regex: /^N/ } }
)#Multiple conditionsdb.bios.find( {
birth: { $gt: new Date('1920-01-01') },
death: { $exists: false }
} )db.bios.find(
{
"name.first": "Yukihiro",
"name.last": "Matsumoto"
}
)db.bios.find( { contribs: { $in: [ "ALGOL", "Lisp" ]} } )
Feel free to reach out to me at : https://www.linkedin.com/in/ashutosh-kumar-9a109864/