How to MongoDB- Query document

In this guide, we will learn how to query document from MongoDB collection.

In MongoDB, the db.collection.find(query, projection) method is used to retrieve documents from a collection. To find documents that match a set of selection criteria, call find() with the parameter.

 

Syntax
     >db.COLLECTION_NAME.find()
ParameterTypeDescription
querydocumentOptional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
projectiondocumentOptional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter. For details, see Projection.

The following operation returns documents in the bios collection where _id equals 5:

 

Example
     db.mycollection.find( { _id: 5 } )

The find() method with no parameters returns all documents from a collection and returns all fields for the documents. For example, the following operation returns all documents in the COLLECTION_NAME

 

Example
     db.COLLECTION_NAME.find({})

In the find() method, if you pass multiple keys by separating them by ‘,’ then MongoDB treats it as AND condition.

 

Syntax
     >db.mycol.find({
      $and: [{key1: value1}, {key2:value2}]
      })

To query documents based on the OR condition, you need to use $or keyword.

 

Syntax
     >db.mycol.find({
       $or: [{key1: value1}, {key2:value2}]
       })

 

Query document in array

To query documents in an array, we can use 3 operators which are given below.

Query Operator Array

NameDescription
$allMatches arrays that contain all elements specified in the query.
$elemMatchSelects documents if element in the array field matches all the specified $elemMatch conditions.
$sizeSelects documents if the array field is a specified size.

 

To specify an $all expression, use the following syntax:

Syntax
     { <field>: { $all: [ <value1> , <value2> ... ] } }

 

To specify an $elemMatch expression, use the following syntax:

Syntax
     { <field>: { $elemMatch: { <query1>, <query2>, ... } } }

 

To specify an $size expression, use the following syntax:

Syntax
     db.collection.find( { field: { $size: 2 } } );

 

Muhsin Yakkiparamban

Muhsin Yakkiparamban is the co-founder of Lauyou Learning. Muhsin holds Bachelor Degree in Civil Engineering from KMCT Calicut.

You may also like...