MongoDB Query Documents

MongoDB Query Documents – db.inventory.find(criteria)  is used to query all MongoDB Documents, or filter them based on a criteria, from a MongoDB Collection.

Examples

Example 1 – Query All Documents in a Collection

To query all documents in a collection, use find() method with empty document as argument.

Following is the syntax of find command to query all documents

db.<collection>.find( {} )

<collection>  is the name of the MongoDB Collection.

Following command queries all documents in people  collection present intutorialkart database

> use tutorialkart
switched to db tutorialkart
> db.people.find({})
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag", "profession" : "Driver" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb6"), "name" : "Bharat", "age" : 24, "place" : "New York", "profession" : "Programmer", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb7"), "name" : "Arya", "age" : 25, "profession" : "Teacher" }
ADVERTISEMENT

Example 2 – Query Documents of a Collection based on a Criteria

Following example demonstrates to query those documents of a Collection that respect a criteria.

Select the database in which the collection is, using USE command.

> use tutorialkart
switched to db tutorialkart

Prepare a criteria to select documents

> criteria={place:"New York"}
{ "place" : "New York" }

Use the criteria with find() method to select those documents that obey the criteria.

> criteria={name:"Manju"}
{ "name" : "Manju" }

Run find(criteria) method

> db.people.find(criteria)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb6"), "name" : "Bharat", "age" : 24, "place" : "New York", "profession" : "Programmer", "bonus" : 250 }

Conclusion

In this MongoDB Tutorial MongoDB Query Documentsdb.inventory.find(criteria)  is used to query all MongoDB Documents, or filter them based on a criteria, from a MongoDB Collection.