MongoDB tutorials

3. Query document

Video tutorial:

First, we will insert a few documents. You can insert documents by calling insert function multiple times, or you can use insertMany function. InsertMany function will receive an array of objects.

db.users.insertMany([ { "name": "Adnan", "age": 27 }, { "name": "Ali", "age": 29}, { "name": "Ahmad", "age": 31 } ])

Now you can see a list of all records using find() function:

db.users.find()

Find() function will return all records, but if you want to filter the data you can pass an object inside find() function as a parameter:

db.users.find({ "age": 27 })

This will return all the records having age equals to 27. Now you can use less than and greater than operators too. For example, if you want to get all the records from users collection having age less than 30 then:

db.users.find({ "age": { $lt: 30 } })

You see now we are passing an object in “age” instead of simple value. The object has an operator $lt which stands for less than and this operator has the value. Similarly, if you want “less than and equal to” then simply write $lte instead of $lt:

db.users.find({ "age": { $lte: 30 } })

This will return all records having age less than and equal to 30. Similarly, we can do greater than clause using $gt:

db.users.find({ "age": { $gt: 30 } })

This will return all records having an age greater than 30. The same can be applied for greater than and equal to using $gte.

Now we will discuss about AND and OR operator. Both operators will receive an array of objects where we will write all the conditions. $and operator will return the records only if every condition in array is true. $or operator will return the records if there is at-least one condition in array is true.

The following query will return the records where name is “Ali” and age is 29:

db.users.find({ $and: [ {"name": "Ali"}, {"age": 29} ] })

Similarly you can use $or operator. Following query will return all the records where name is Ali or Ahmad:

db.users.find({ $or: [ {"name": "Ali"}, {"name": "Ahmad"} ] })