MongoDB find multiple conditions

In this MongoDB tutorial, we are going to learn “MongoDB find multiple conditions”. We will also cover this topic with different operations and examples. These are the following topics that we are going to cover in this tutorial:

  • MongoDB find query with multiple conditions
  • MongoDB find multiple conditions
  • MongoDB findone multiple conditions
  • MongoDB compass find multiple conditions
  • MongoDB find multiple conditions and
  • MongoDB find multiple conditions or
  • MongoDB find multiple conditions match
  • MongoDB find multiple conditions python

MongoDB find query with multiple conditions

The find query in MongoDB is used to choose documents from a collection, inspect them, and return a cursor to the selected documents.

Syntax:

db.collection.find(query, projection)

Let’s discuss the query(syntax) in detail:

ParameterTypeDescription
querydocumentOptional, used to specify selection filter using query operators. To return all documents in a collection or pass an empty document.
projectiondocumentOptional, documents that match the query filter and to return all fields in the matching documents.

Note that, the find() method “returns documents” the method is returning a cursor to the documents.

You will more understand with the help of an example so let’s get started:

Example:

In the example, we apply multiple conditions to documents and find the documents accordingly.

The following documents are inserted into the inventory collection:

db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

After inserting the documents into the inventory collection. We apply the multiple conditions as per the question requirement and retrieve the result by using the find() method.

> db.inventory.find(
    {
    qty : {  $lt: 30 }},
    { item: 1, tags: 1}
)

The following operation returns all documents from the inventory collection where the qty field is greater than 30 and returns only these two fields item and tags. You can add any field name that you want to return.

After executing the query in the MongoDB shell, we got the output as:

MongoDB find query with multiple conditions
MongoDB find query with multiple conditions

This is the easiest way of applying multiple conditions using the find() method and we have successfully got the result as per the given condition.

Read: MongoDB update the documents

MongoDB find multiple conditions

In MongoDB, To access the documents of a collection we use the find() method. In this method, you can give any conditions if you want to and get the result as per the condition.

You will more understand with the help of an example so let’s get started:

Example:

In the example, we apply multiple conditions to documents and find the documents accordingly.

The following documents are inserted into the data collection:

> db.data.insertMany([
   {
       "_id" : 1,
       "name" : {
           "first" : "John",
           "last" : "Backus"
       },
       "birth" : ISODate("1924-12-03T05:00:00Z"),
       "death" : ISODate("2007-03-17T04:00:00Z"),
       "contribs" : [
           "Fortran",
           "ALGOL",
           "Backus-Naur Form",
           "FP"
       ],
       "awards" : [
           {
               "award" : "W.W. McDowell Award",
               "year" : 1967,
               "by" : "IEEE Computer Society"
           },
           {
               "award" : "National Medal of Science",
               "year" : 1975,
               "by" : "National Science Foundation"
           },
           {
               "award" : "Turing Award",
               "year" : 1977,
               "by" : "ACM"
           },
           {
               "award" : "Draper Prize",
               "year" : 1993,
               "by" : "National Academy of Engineering"
           }
       ]
   },
   {
       "_id" : ObjectId("51df07b094c6acd67e492f41"),
       "name" : {
           "first" : "John",
           "last" : "McCarthy"
       },
       "birth" : ISODate("1927-09-04T04:00:00Z"),
       "death" : ISODate("2011-12-24T05:00:00Z"),
       "contribs" : [
           "Lisp",
           "Artificial Intelligence",
           "ALGOL"
       ],
       "awards" : [
           {
               "award" : "Turing Award",
               "year" : 1971,
               "by" : "ACM"
           },
           {
               "award" : "Kyoto Prize",
               "year" : 1988,
               "by" : "Inamori Foundation"
           },
           {
               "award" : "National Medal of Science",
               "year" : 1990,
               "by" : "National Science Foundation"
           }
       ]
   },
   {
       "_id" : 3,
       "name" : {
           "first" : "Grace",
           "last" : "Hopper"
       },
       "title" : "Rear Admiral",
       "birth" : ISODate("1906-12-09T05:00:00Z"),
       "death" : ISODate("1992-01-01T05:00:00Z"),
       "contribs" : [
           "UNIVAC",
           "compiler",
           "FLOW-MATIC",
           "COBOL"
       ],
       "awards" : [
           {
               "award" : "Computer Sciences Man of the Year",
               "year" : 1969,
               "by" : "Data Processing Management Association"
           },
           {
               "award" : "Distinguished Fellow",
               "year" : 1973,
               "by" : " British Computer Society"
           },
           {
               "award" : "W. W. McDowell Award",
               "year" : 1976,
               "by" : "IEEE Computer Society"
           },
           {
               "award" : "National Medal of Technology",
               "year" : 1991,
               "by" : "United States"
           }
       ]
   },
   {
       "_id" : 4,
       "name" : {
           "first" : "Kristen",
           "last" : "Nygaard"
       },
       "birth" : ISODate("1926-08-27T04:00:00Z"),
       "death" : ISODate("2002-08-10T04:00:00Z"),
       "contribs" : [
           "OOP",
           "Simula"
       ],
       "awards" : [
           {
               "award" : "Rosing Prize",
               "year" : 1999,
               "by" : "Norwegian Data Association"
           },
           {
               "award" : "Turing Award",
               "year" : 2001,
               "by" : "ACM"
           },
           {
               "award" : "IEEE John von Neumann Medal",
               "year" : 2001,
               "by" : "IEEE"
           }
       ]
   },
   {
       "_id" : 5,
       "name" : {
           "first" : "Ole-Johan",
           "last" : "Dahl"
       },
       "birth" : ISODate("1931-10-12T04:00:00Z"),
       "death" : ISODate("2002-06-29T04:00:00Z"),
       "contribs" : [
           "OOP",
           "Simula"
       ],
       "awards" : [
           {
               "award" : "Rosing Prize",
               "year" : 1999,
               "by" : "Norwegian Data Association"
           },
           {
               "award" : "Turing Award",
               "year" : 2001,
               "by" : "ACM"
           },
           {
               "award" : "IEEE John von Neumann Medal",
               "year" : 2001,
               "by" : "IEEE"
           }
       ]
   }
  
] )

After inserting the documents into the collection, we apply the find() method to retrieve the documents of the collection.

> db.data.find( {
   birth: { $gt: new Date('1930-01-01') },
   death: { $exists: true}
} )

The following operation returns all documents from the data collection where the birth field is greater than the new Date(‘1930-01-01’) and the death field does exist:

After executing the query in the MongoDB shell, we got the output as:

MongoDB find query with multiple conditions
MongoDB find multiple conditions example

Here, we successfully got the result as per the given condition. This way you can apply the multiple conditions using the find() method and get the output as per your condition.

Read: How to drop a database in MongoDB

MongoDB findone multiple conditions

MongoDB provides a findOne() method that is used to return one document that satisfies the specified query criteria on the collection.

If the query is satisfied by multiple documents, this method returns only the first document, and if the query is not satisfied by any documents, the method returns null.

Syntax:

db.collection.findOne(query, projection)

Let’s discuss the query in detail

ParameterTypeDescription
querydocumentsOptional, query selection criteria
projectiondocumentsOptional, Drop this parameter to return
all fields in the matching documents.

Note that, It returns one document that satisfies the criteria specified as the first argument to this method.

If you define the projection parameter then findOne() returns a document that includes projection fields. The _id field is always included except you explicitly exclude it.

Example:

In this example, you will understand how can we use the findOne() method and retrieve the result when given multiple conditions.

The following documents are inserted into the car collection:

db.car.insertMany([
{_id:1,name:"Audi",color:"Red",cno:"H101",mfdcountry:"Germany",speed:75 },
{_id:2,name:"Swift",color:"Black",cno:"H102",mfdcountry:"Italy",speed:60 },
{_id:3,name:"Maruthi800",color:"Blue",cno:"H103",mfdcountry:"India",speed:70 },
{_id:4,name:"Polo",color:"White",cno:"H104",mfdcountry:"Japan",speed:65 },
{_id:5,name:"Volkswagen",color:"JetBlue",cno:"H105",mfdcountry:"Rome",speed:80 }       
])

Now, we apply the findOne() method with conditions and return the result:

> db.car.findOne(
    {
    speed: { $gt: 65}},
    { name: 1, mfdcountry: 1}
    )

Here, you can see we apply the findOne() method and return only those documents where speed is greater than 65 and return only these two fields name and mfdcountry. You can define any field name that you want to return.

After executing the query in the MongoDB shell, we got the output as:

MongoDB findone multiple conditions
MongoDB findOne multiple conditions

Here, we return document successfully and if there are multiple documents then that situation the findOne() method return only the first one document.

Read: How to create new database in MongoDB

MongoDB compass find multiple conditions

In MongoDB Compass, you can apply multiple conditions and easily find the documents. You will more understand with the help of an example so let’s get started:

Example:

In this example, we insert some documents into the collection and apply multiple conditions using MongoDB Compass.

You need to follow the following steps:

  • Open MongoDB Compass
  • Select the database and collection for applying multiple conditions
  • These are some documents we inserted into the developers collection
db.developers.insertMany([
{ _id: 20, devname: "John Wick", tools: "Visual Studio", born: 1948 },
{ _id: 21, devname: "Ganesh Roy", tools: "Net Beans", born: 1945 },
{ _id: 22, devname: "Deeksha Raul", tools: "Unity 3D", born: 1954 }
])
  • Now check the documents in MongoDB Compass
MongoDB compass find multiple conditions
documents inserted into developers collection

Here, we selected the database and collection, test, developers respectively. And you can see documents are also available in the developers‘ collection.

  • Now, apply the condition so click on OPTIONS button
MongoDB compass find multiple conditions example
MongoDB compass find multiple conditions

Here, we have applied the conditions as display those fields where the born year is greater than 1945 and display two fields devname and born and sort the result according to devname ascending order.

  • After applying the conditions click on FIND button
  • See the ouput below the applied condition block.

We successfully find the documents by applying multiple conditions using MongoDB Compass.

Read: MongoDB backup and restore

MongoDB find multiple conditions and

In MongoDB, we can apply the multiple conditions using the and operator. By applying the and operation we will select all the documents that satisfy all the condition expressions.

  • We can use this operator in methods like find(), update() , etc as per the requirement.
  • We can also use this operator with text queries and sort operations.

Syntax:

This is the syntax that is used while using the and operator:

{ $and: [{ <expression1> },{ <expression2> }, ... ,{ <expressionN> }] }

So let’s understand with the help of an example:

Example:

The following documents are inserted into the survey collection:

> db.survey.insertMany([
{
   "StudentName" : "John",
   "StudentAddress" : "US",
   "StudentAge" : 24
},
{
   "StudentName" : "David",
   "StudentAddress" : "UK",
   "StudentAge" : 27
},
{
   "StudentName" : "Carol",
   "StudentAddress" : "UK",
   "StudentAge" : 29
},
{
   "StudentName" : "Bob",
   "StudentAddress" : "US",
   "StudentAge" : 24
}
])

See the documents of survey collection by using MongoDB Shell:

MongoDB find multiple conditions and example
Insert documents into a collection

Now, we apply multiple conditions with the help of $and operator and find the documents.

> db.survey.find({
     $and: [
        { "StudentAddress": "US"},
        { "StudentAge": 24}
     ]
}).pretty()

Here, we applied $and operation and find those documents where StudentAddress is the US and StudentAge is 24.

Now, See the execution of the above code in the MongoDB shell:

MongoDB find multiple conditions and
MongoDB find multiple conditions and

We have got the result successfully as per the given condition. You can use the $and operator and retrieve the documents according to the condition.

Read: How does MongoDB create collection

MongoDB find multiple conditions or

In MongoDB, the or operator is used to select or retrieve only those documents that match at least one of the given expressions.

  • We can also use this operator in method like find(), update() etc as per the requirements.
  • We can also use this operator with text queries and sort operations.
  • We can also nest $or operation.

Syntax:

This is the syntax that is used while working with or operator:

{ $or: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }

Let’s understand the example:

Example:

The following documents are inserted into the student collection:

> db.student.insertMany([
      { 
        "name"      : "Sophia",
        "age"       : 22,

        "gender"    : "Female",
        "timestamp" : new ISODate("2021-07-01" )
      },
      { 
        "name"      : "Isabella",
        "age"       : 21,

        "gender"    : "Female",
        "timestamp" : new ISODate("2021-09-21" )
      },
      {
        "name"      : "Harper",
        "age"       : 27,

        "gender"    : "Male",
        "timestamp" : new ISODate("2021-05-22")
      }
]) 

After inserting these documents into the collection, we apply $or operator and find only condition specified documents.

> db.student.find(
    { $or: [{ age: {$gt: 25}},
    { gender: "Female"}]}
).pretty()

Here, we apply the $or operation and show only those documents where age is greater than 25 and gender is Female.

The or operator retrieves all those documents that match at least one of the given expressions.

Now, See the execution of the above code in the MongoDB shell:

MongoDB find multiple conditions or
MongoDB apply $or operator

We have got the result successfully as per the given condition. You can use the $or operator and retrieve the documents according to the condition.

Read: Pros and cons of MongoDB

MongoDB find multiple conditions match

In MongoDB, we can apply the multiple conditions using the find() method and retrieve only those documents that match our documents.

The find() method is used to select the documents from a collection and return a cursor to the selected documents. Here, the cursor indicates a pointer that points to a document. when we use the find() method to returns a pointer on the selected documents and returns one by one.

Let’s understand with the help of an example:

Example:

In this example, we apply multiple conditions to the documents using the find() method and return documents as per the condition.

The following documents are inserted into the person collections

> db.person.insertMany([
{
        "FName" : "David",
        "LName" : "Smith",
        "Age" : 24,
        "Gender" : "Male"
},
{
        "Name" : "Alex",

        "LName" : "Miller",
        "Age" : 22,
        "Gender" : "Male"
},
{
        "Name" : "Sophia",
        "LName": "Miler",
        "Age" : 22,
        "Gender" : "Female"
},
{
        "Name" : "Emma",

        "LName" : "Kramer",
        "Age" : 23,
        "Gender" : "Female"
}
])

Check the documents of the collection by using MongoDB Shell:

MongoDB find multiple conditions match
Insert documents into a collection

Now, we apply multiple conditions to these documents and return only specific documents by using the find() method.

> db.person.find(
     { "Gender": "Male",
       "Age" : { $gte: 22}} 
)

Here, we applied conditions to display only those documents where Age is greater than equal to 22 and Gender is Male.

After executing the code you will get the output as given below:

MongoDB find multiple conditions that match

We successfully obtain the specific documents as per the condition specified in the find() method.

Read: Create tables in MongoDB

MongoDB find multiple conditions python

In Python, we can easily access the MongoDB database and apply multiple conditions by using the $and operation to the documents. And, for retrieving the documents we use the find() method.

You will more understand with the help of an example so let’s get started:

Example:

In this example, we access only some specific documents after applying conditions to the documents by using python.

The following documents are inserted into the survey collection

> db.survey.insertMany([
{
   "StudentName" : "John",
   "StudentAddress" : "US",
   "StudentAge" : 24
},
{
   "StudentName" : "David",
   "StudentAddress" : "UK",
   "StudentAge" : 27
},
{
   "StudentName" : "Carol",
   "StudentAddress" : "UK",
   "StudentAge" : 29
},
{
   "StudentName" : "Bob",
   "StudentAddress" : "US",
   "StudentAge" : 24
}
])

We inserted these documents into the survey collection in the company database.

import pymongo

client = pymongo.MongoClient('localhost', 27017)
db = client['company']
col = db['survey']

doc = col.find({
        "$and": [
            { "StudentAddress": "US"},
            { "StudentAge": 24}]
    })
for result in doc:
    print(result)

Here, we import the pymongo library to make the connection between Python and MongoDB databases. After that use the class MongoClient of pymongo to start the MongoDB server.

And we applied $and operation and find those documents where StudentAddress is the US and StudentAge is 24.

After executing the code you will get the output as given below:

MongoDB find multiple conditions python
MongoDB find multiple conditions using python

Output:

MongoDB find multiple conditions python example
MongoDB find multiple conditions using python

We successfully obtain the specific documents as per the condition specified in the find() method using python.

You may also like to read the following MongoDB tutorials.

In this MongoDB tutorial, we have covered how we can find particular documents by applying multiple conditions to the documents. We understood this with different operations and examples. And, we have discussed the following topics in detail:

  • MongoDB find query with multiple conditions
  • MongoDB find multiple conditions
  • MongoDB findone multiple conditions
  • MongoDB compass find multiple conditions
  • MongoDB find multiple conditions and
  • MongoDB find multiple conditions or
  • MongoDB find multiple conditions match
  • MongoDB find multiple conditions python

Leave a Comment