Advanced Querying in MongoDB

Reading Time : ~ .

Querying with MongoDB

First, To get start with MongoDB, you need to install it and connect to the MongoDB shell.
Querying:
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: "xyz@gmail.com",
  intrests: {
    name: "painting",
    type: "art"
  }
  skills: [ "mongodb", "mysql" ],
}

Wrapped Queries:

Like Query:

	db.user.find({"name": "mp"})
	db.user.findOne({"email": "xyz@gmail.com"})

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

	db.user.find().sort({"age":-1})

Limit Query:

	db.user.find().limit(10)

Count Query:

	db.user.find().count()

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:

	db.user.update(

	   { _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

	db.products.update(
	   { _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
	db.company.update({_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:

	db.company.update({_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.

db.company.update( { _id: 1 }, { $pop: { employees: -1 } } )    it removes "emp1" in the employees array
db.company.update( { _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.

    db.company.find(
        {"employees":
            {"$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},
                {"intrests.name": "painting"}
            ]
    })

AND Queries:

1. "$all" can be used to query for a variety of values for a single key.

        db.company.find(
                {"employees":
                    {"$all": ["emp1", "emp2"]}
                })

Below query will do exact match, considering order also, if order changes it will not show any result

   db.company.find(
                {"employees":
                    ["emp1", "emp2"]
                })
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Full text search in mongodb Nikhila Mergu

Full text search is a custom implementation created by the MongoDB developers as a specific index type

Full text search as an index type when ...

Continue Reading...
MongoDB CRUD operations with Python (Pymongo) Rakesh babu Podishetty

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

Continue Reading...
group() vs aggregation framework vs MapReduce in mongodb Ashwin Kumar

The group() command, Aggregation Framework and MapReduce are collectively aggregation features of MongoDB. group(): Group Performs simple aggregation operations on a collection documents. Group is ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties