MongoDB - Select Documents from collection in MongoDB using Robo 3T - TechDB

Latest

All about Database Programming, Performance Tuning and Best Practices.

BANNER 728X90

Friday, 6 March 2020

MongoDB - Select Documents from collection in MongoDB using Robo 3T




MongoDB - Select Documents from collection in MongoDB using Robo 3T

To read all the documents from collection we can use below command.
Db.collection Name.find()
Our collection name is inventory, so that we can write as below
Db.inventoy.find()
It will return all the documents from this collection.

We can use different filter condition to filter the documents.

ConditionSyntaxRDBMS equivalent
Equal{&ltkey&gt:&ltvalue&gt}Where col = value
Less than{&ltkey&gt:{$lt:&ltvalue&gt}}Where col < value
Less than equal{&ltkey&gt:{$lte:&ltvalue&gt}}Where col <= value
Greater than{&ltkey&gt:{$gt:&ltvalue&gt}}Where col > value
Greater than equal{&ltkey&gt:{$gte:&ltvalue&gt}}Where col >= value
Not equal{&ltkey&gt:{$ne:&ltvalue&gt}}Where col != value

Example - Select all the documents from collection where status = “D”

db.inventory.find({"status":"D"}) 



Example - Select all the documents from collection where status = “D” and qty = 100

db.inventory.find({"status":"D","qty":100})

Internally MongoDB filter based on the first filter criteria “status” and then trying to filter “qty” column.


Example - Lets find all the documents from collection where Qty is less than 25.

db.inventory.find({"qty":{$lt:25}})



Example - Now we will find the documents from Collection where Qty is less than equal to 25. (<= 25)

db.inventory.find({"qty":{$lte:25}})



Example - Next we will find the documents from Collection where Qty is Geater Than 25. (> 25)

db.inventory.find({"qty":{$gt:25}})



Example - Next we will find the documents from Collection where Qty is Geater Than equal to 25. (>= 25)

db.inventory.find({"qty":{$gte:25}})



Example - Next we will find the documents from Collection where Qty is Not Equal to 10. (!= 10)

db.inventory.find({"qty":{$ne:10}})



Example - Next we will find the documents from Collection where Qty is Not Equal to 10 and Greater Than 50.  (!= 10 and > 50)

db.inventory.find({"qty":{$ne:10,$gt:50}})



We can also combined multiple conditions as below.

Example - Lets find the documents from Collection where Qty is Not Equal to 10 and Greater Than 50 and than filter where Status = “D”.  (!= 10 and > 50 the Status = “D”)

db.inventory.find({"qty":{$ne:10,$gt:50},"status":"D"})




No comments:

Post a Comment