Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
MongoDB

Advanced Querying in MongoDB

2022-07-21

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"]
                })