Query Documents in MongoDB

MongoDB query document is the topic that we are going to discuss here. This tutorial is for those who are beginners and want to learn how to query in MongoDB.

In this tutorial, we are going to use MongoDB Node.js driver to perform query operations.

We are assuming here you have MongoDB installed in your computer. If not then make sure to install it by reading the detailed tutorial from here.

So let’s get started to query documents from a collection using find() method.

We will use some static data set to perform the query. So, insert the data given below in a users collection.

db.collection('users').insertMany([
{
    name: 'Avinash',
    age: 28,
    experience: { node: '6 years', mongo: '6 years', express: '6 years' },
    email: 'avinashk@xxxx.com',
    blood: 'A+'
  },
  {
    name: 'Alok',
    age: 25,
    experience: { node: '4 years', mongo: '4 years', express: '4 years' },
    email: 'alok@xxxx.com',
    blood: 'B+'
  },
  {
    name: 'Piyush',
    age: 23,
    experience: { node: '5 years', mongo: '5 years', express: '5 years' },
    email: 'avinashk@xxxx.com',
    blood: 'B+'
  },
  {
    name: 'Gaurav'
    age: 22,
    experience: { node: '3 years', mongo: '3 years', express: '3 years' },
    email: 'gaurav@xxxx.com',
    blood: 'A+'
  },
  {
    name: 'Ashwin',
    age: 23,
    experience: { node: '2 years', mongo: '2 years', express: '2 years' },
    email: 'ashwin@xxxx.com',
    blood: 'B+'
  }
]);

Select All Documents Using find()

If you want to select all documents from a collection, you can use MongoDB find() method. To do that you need to pass an empty document as a parameter to the find method.

This empty document as a parameter determines the select documents criteria.

Now, see the example below:

const cursor = db.collection('users').find({});

The above query is similar to SQL syntax:

SELECT * FROM users

You can find a detailed guide about find() method here.

MongoDB Equality Condition

You need to use <field>:<value> expressions instead of empty document to specify the equality condition.

See the syntax below which select all the users from the users collection whose age is equal to 23.

const cursor = db.collection('users').find({ age: 23 });

The query above is as same as SQL syntax:

SELECT * FROM users WHERE 'age' = 23

MongoDB Query Condition Using Query Operators

Let’s say we want to fetch all the users who come under certain blood group. See the syntax below:

const cursor = db.collection('users').find({
 blood: { $in: ['A+', 'B+'] }
});

The above code fetches all the users whose blood group is ‘A+’ & ‘B+’.

You can also specify a single blood group type or multiple blood groups by a comma separated to get the multiple blood group type of users.

This query is similar to SQL syntax given below:

SELECT * FROM 'users' WHERE 'blood' in ("A+", "B+")

MongoDB Query: AND Condition

At the time of querying database, It is very normal to match multiple conditions to get details.

And, this can be done easily by using MongoDB AND condition.

See the syntax below:

const cursor = db.collection('users').find({
  blood: 'B+',
  age: { $lt: 25 }
});

By using the above query we can fetch all the users whose blood group is ‘B+’ & age is less than 25. In this condition, both scenarios should match equally.

In SQL, you can write the above query like below:

SELECT * FROM users WHERE 'blood' = "B+" AND 'age' < 25

OR Condition in MongoDB

By using the $or operator, you can create a query that joins each clause with a logical OR operator. In this condition, at least one scenario should match.

See the example code below which retrieves all the documents in the users’ collection where the blood group equals to “A+” or age is less than 25.

const cursor = db.collection('users').find({
  $or: [{ blood: 'A+' }, { age: { $lt: 25 } }]
});

The above query corresponds to the following SQL statement

SELECT * FROM users WHERE 'blood' = "A+" OR age < 25

MongoDB Query: AND, OR Conditions

In the below example, we are going to create a query that selects all documents in the collection where the blood group equals “B+” and either age is less than 26 or the user name starts with the character ‘A’.

const cursor = db.collection('users').find({
  blood: 'B+',
  $or: [{ age: { $lt: 26 } }, { name: { $regex: '^A' } }]
})

This is the same query as shown below in SQL.

SELECT * FROM users WHERE 'blood' = "B+" AND ( age < 26 OR name LIKE "A%")

Conclusion

In MongoDB query, the collection.find() method returns a cursor. You can find details about cursor here.
There is one more method called collection.findOne() which is used to read documents from a collection.
You can also fetch documents from a collection and modify data according to your needs using MongoDB aggregation.

Finally, a query document from MongoDB collection is over. Hope you liked this tutorial. Feel free to ask your question regarding the MongoDB query in the comment section.

 

 

 

 

Leave a Reply