MongoDB Query Documents

MongoDB Query Documents means read operations retrieves documents from a collection; i.e. queries a collection for documents. MongoDB provides find() and findOne() mtehopds to read document(s) from a collection.

MongoDB find() Syntax:

db.collection.find(query, projection)

Where
query: Specifies selection filter using query operators.
projection: Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter.

MongoDB Query Documents Examples:

Lets create a collection by executing below statement in your database.

db.products.insert([ {"item" : "card", "qty" : 15 }, { "item" : "envelope", "qty" : 20 }, { "item" : "stamps", "qty" : 30 }, { "_id" : 10, "item" : "large box", "qty" : 20 }, { "_id" : 11, "item" : "small box", "qty" : 55 }, { "_id" : 12, "item" : "medium box", "qty" : 30 }] )

1. To get all documents from collection use find() or find({})

db.products.find() or db.products.find({})

2. To get documents from collection where qty is more than 25.

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

3. Find the documents where id equals to 10 in products collection.

db.products.find({_id:10})

4. Find the collections which contains price field in the products collection.

db.products.find({qty:{$exists:true}})

If field is there in a collection, then it will give matching documents otherwise no documents.

5. Find the documents where item contains name like ‘box’ in any place and qty is greater than 25.

db.products.find({$and:[{item:{$regex:/box/}},{qty:{$gt:25}}]})

First part of above query filters the item field which contains box, second part check qty is greater than 25.