By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content .
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Advanced Querying in MongoDB

Querying with MongoDB

First, To get start with MongoDB, you need to install it and connect to the MongoDB shell.
Putting stuff in the database is all well and good, but you’ll probably want to query the database to get data from it.

  • Queries using find() or findone() functions.
  • You can query for ranges, set inclusion, inequalities, and more by using $ conditionals
  • All queries return cursor.

Cursor: It returns all documents matching a specific query. To access the documents, you need to iterate the cursor.

Consider a collection "User" with the following document

  _id: 1,
  name: "mp",
  age: 10,
  email: "",
  intrests: {
    name: "painting",
    type: "art"
  skills: [ "mongodb", "mysql" ],

Wrapped Queries:

Like Query:

	db.user.find({"name": "mp"})
	db.user.findOne({"email": ""})

Differences between find() and findone()

The two queries you are executing are very different. A find query returns a cursor, and has no actual data is returned (only the cursor information). If you call findOne, then you are actually returning the data and closing the cursor.

Sort Query: 1 for ascending sort, -1 for descending sort


Limit Query:


Count Query:


Query Using Modifiers:

Not Equal Modifier($ne):

	db.user.find({"age": {$ne: 20}})    # Returns Cursor with the documents having age not equal to 20

Greater/Less than Modifier($gt, $lt, $gte, $lte):

	db.user.find({"age": {$gt: 20}})
	db.user.find({"age": {$lt: 20}})
	db.user.find({"age": {$gte: 20}})
	db.user.find({"age": {$lte: 20}})

Increment Modifier:

	db.User.update({"name": "mp"}, {"$inc": {"age": "newValue"}})       Updates the value of age which collection having name has "mp"

Set Modifier: "$set" will add a new field with the specified value, provided that the new field does not violate a type constraint.

Set fields in Embedded Documents:


	   { _id: 1 },
	   { $set: { "intrest.type": "zzz" } }

Set Elements in Array: This updates the value specified, second element(array index of 1) in the skills field

	   { _id: 1 },
	   { $set:
	        "skills.1": "newValue",

Key-Value will be created if the key does not exists in the case of both "$inc" and "$set"

Push Modifier($push):

"$push" adds an element to the end of an array if the specified key exists and creates a new array if it does not.

Append Multiple Values to an Array:

	db.user.update({ "name": "mp" },
	               { $push:
	                   { friends:
	                       { $each: [ "xyz", "xyz", "xyz" ]

This appends each element of [ "xyz", "xyz", "xyz" ] to the friends array for the document where the name field equals mp.

AddToSet Modifier($addToSet):

The "$addToSet" operator adds a value to an array unless the value is already present, if the value is in the array it will not append.

 { _id: 1, company_name: "micropyramid", employees: [ "emp1", "emp2" ] } This is the collection of Company{_id: 1},
	        { $addToSet:
	            { employees: "emp3" }

This appends "emp3" to the array employees of the company name "micropyramid".

result: { _id: 1, company_name: "micropyramid", employees: [ "emp1", "emp2", "emp3" ] }

Using "$each" Modifier:{_id: 1},
	{ $addToSet:
	    { employees:
	        {"$each": ["emp3", "emp4", "emp1"]
result: { _id: 1,
          company_name: "micropyramid",
          employees: [ "emp1", "emp2", "emp3", "emp4" ]

Pop Modifier($pop):
"$pop" Removes first or the last element of an array, -1 to remove the first element of an array and 1 to remove the last element in an array. { _id: 1 }, { $pop: { employees: -1 } } )    it removes "emp1" in the employees array { _id: 1 }, { $pop: { employees: 1 } } )   it removes "emp4" in the employees array

OR Queries:

There are two ways to do OR query "$or"
1. "$in" can be used for a variety of values for a single key.
            {"$in": ["emp1", "emp2"]}
2. "$or" can be used to query for any of the given valuesacross multiple keys
    ex: db.user.find({"$or":
                {"age": 10},
                {"": "painting"}

AND Queries:

1. "$all" can be used to query for a variety of values for a single key.
                    {"$all": ["emp1", "emp2"]}

Below query will do exact match, considering order also, if order changes it will not show any result
                    ["emp1", "emp2"]
    Posted On
  • 26 January 2014
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Celery Flower to monitor task queue

Celery is a task queue that is to built an asynchronous message passing system. It can be used as a bucket where programming tasks can ...

Continue Reading...
Multifactor Authentication with Django MFA using Google Authenticator

Use Django Multi-Factor Authentication method to verify user identity with more than one authentication methods. It can be used for user login, any transactional methods ...

Continue Reading...
MongoDB CRUD operations with Python (Pymongo)

MongoDB with Python - Connection establishment, Create, Update, Retrieve and Delete operations explained with sample code.

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties