The MongoDB Query Language (MQL)
LESSON
Google slide deck available here
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
(CC BY-NC-SA 3.0)
Overview
At a Glance
Suggested Uses
Learning Objectives
Length:
70 minutes
Level:
Intermediate
Prerequisites:
At the end of this lesson, learners will be able to:
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
(CC BY-NC-SA 3.0)
This lesson is a part of the courses Querying in Non-Relational Databases and Introduction to Modern Databases with MongoDB.
This lesson includes exercises
Follow along using these tools
Create a Database
Connect to Your Database
For more instructions on how to use MongoDB Atlas with your students, see Atlas for Educators
MongoDB Query Language
Simple syntax
Designed to query documents
Only queries a single collection
MongoDB Query Language
MQL is designed for single collection queries and it is typically used for creating, reading, updating, or deletion (CRUD) operations.
MQL query operators:
MQL Find()
MQL Find()
db.<collection>.find()
Query filter document
db.collection.find({ <field1>: <value1>, ... })
Specifying query operators
db.<collection>.find({ <field1>: { <operator1>: <value1> }, ... })
MQL Find()
db.<collection>.find()
Query filter document
db.collection.find({ <field1>: <value1>, ... })
Specifying query operators
db.<collection>.find({ <field1>: { <operator1>: <value1> }, ... })
MQL Find()
db.<collection>.find()
Query filter document
db.collection.find({ <field1>: <value1>, ... })
Specifying query operators
db.<collection>.find({ <field1>: { <operator1>: <value1> }, ... })
MQL Find(): Important Note
The collection is implicit in MQL based on the query’s criteria.
Quiz
Quiz
Which of the following is true for MongoDB MQL find()?
Quiz
Which of the following is true for MongoDB MQL find()?
Quiz
Which of the following is true for MongoDB MQL find()?
This is incorrect. The collection is explicitly specified as part of the find syntax, specifically db.collection.find() rather than as part of the query filter document.
Quiz
Which of the following is true for MongoDB MQL find()?
This is correct. Query operators can be used to specify conditions within the query filter document.
Quiz
Which of the following is true for MongoDB MQL find()?
This incorrect. The syntax of MQL find() limits the query to a single specified collection.
MQL Query Exercise
Using MQL Exercise
Let’s use MQL to find people whose age is below 30.
We’ll walk through:
We’ll do these via the MongoDB Shell.
db.people.find(
{
“age”: { $lt: 30 }
}
)
Let’s find the fields in our documents
db.people.find(
{
“age”: { $lt: 30 }
}
)
With the age field value being $lt (less than) 30
>>> db.people.insertMany([{ "user_id": "Eoin", "age": 29, "Status": "A"}, { "user_id": "Daniel", "age": 25, "Status": "A", "Country": "USA" }])
…
{
acknowledged : true,
insertedIds : [
ObjectId(5f11c32ae89fad25d8875c1c),
ObjectId(5f11c32ae89fad25d8875c1d)
]
}
Let’s insert some real data on people!
MQL: Exercise
Let’s find people whose age is below 30
>>> db.people.find({"age":{"$lt":30}})
{ "_id": ObjectId(5f11c32ae89fad25d8875c1c), "user_id" : "Eoin", "age" : 29, "Status" : "A"}
{ "_id": ObjectId(5f11c32ae89fad25d8875c1d), "user_id" : "Daniel", "age" : 25, "Status" : "A", "Country" : "USA" }
MQL: Exercise
Find the people whose age is great than ($gt) 25.
>>> db.people.find({"age":{"<a>":<b>}})
{ "_id": ObjectId(5f11c32ae89fad25d8875c1c), "user_id" : "Eoin", "age" : 29, "Status" : "A"}
Using the same window, change <a> to the operator for greater than.
Change <b> to the value necessary to find all people whose age is greater than 25.
MQL: Exercise
Create Read Update Delete (CRUD)
MQL Create
insertOne(): Insert one document into a collection.
insertMany(): Insert an array of documents into a collection.
writeConcern: Sets the level of acknowledgment requested from MongoDB for write operations.
ordered: For insertMany() �there is an additional option �for controlling whether the documents are inserted in ordered or unordered fashion.
>> db.cows.insertOne({name: "daisy", milk: 8}, {writeConcern: {w: "majority"}})
{
"acknowledged" : true,
"insertedId" : ObjectId("5f4e0c5b2d4b45b7f11b6d50")
}
>>> db.cows.insertMany([{name: "buttercup", milk: 9}, {name: "rose", milk: 7}], {writeConcern: {w: "majority"}, ordered: false})
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5f4e0ce52d4b45b7f11b6d51"),
ObjectId("5f4e0ce52d4b45b7f11b6d52")
]
}
Example: MQL Create
MQL Read
find(): Selects documents and returns cursor.
findOne(): Returns first document that satisfies criteria.
findAndModify(): Modifies and returns a single document.
findOneAndDelete(): Deletes & returns the deleted document.
findOneAndUpdate(): Updates a single document.
findOneAndReplace(): Replaces a single document.
>>> db.cows.findAndModify({query: {name: "daisy", milk: 8}, update: { $set: {milk: 12} }})
{
"_id" : ObjectId("5f4e0c5b2d4b45b7f11b6d50"),
"name" : "daisy",
"milk" : 8
}
Example: MQL Read
>> db.cows.find({name: "daisy", milk: 8})
{ "_id" : ObjectId("5f4e0c5b2d4b45b7f11b6d50"), "name" : "daisy", "milk" : 8 }
>>> db.cows.find({name: "daisy", milk: 12})
{ "_id" : ObjectId("5f4e0c5b2d4b45b7f11b6d50"), "name" : "daisy", "milk" : 12 }
MQL Update
updateOne(): Update one document into a collection
updateMany(): Update an array of documents into a collection.
>>> db.cows.find({})
{ "_id" : ObjectId("5f4e0c5b2d4b45b7f11b6d50"), "name" : "daisy", "milk" : 9 }
{ "_id" : ObjectId("5f4e0ce52d4b45b7f11b6d51"), "name" : "buttercup", "milk" : 10 }
{ "_id" : ObjectId("5f4e0ce52d4b45b7f11b6d52"), "name" : "rose", "milk" : 8 }
Example: MQL Update
>>> db.cows.updateOne({name: "daisy", milk: 12},{ $set: {milk: 8} })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>>> db.cows.updateMany({}, {$inc: {milk: 1}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }
MQL Delete
deleteOne(): Deletes one document from a collection.
deleteMany(): Deletes many documents from a collection.
writeConcern: Sets the level of acknowledgment requested from MongoDB for write operations.
>>> db.cows.deleteOne({milk: 9})
{ "acknowledged" : true, "deletedCount" : 1 }
>>> db.cows.deleteMany({}, {writeConcern: {w: "majority"}})
{ "acknowledged" : true, "deletedCount" : 2 }
Example: MQL Delete
MQL: xxxMany ( )
Create: insertMany()
Update: updateMany()
Delete: deleteMany()
The Many variants apply to multiple records, however, insertMany() takes an Array of documents.
CRUD: MQL Exercise
>>> cowCol = db.getCollection("cow")
Test.cow
>>> cowCol.drop()
>>> for(c=0;c<10;c++) {
cowCol.insertOne({ name: "daisy", milk: c} )
}
{
acknowledged : true,
insertedIds : ObjectId(5f2aefa8fde88235b959f0b1e),
}
>>> cowCol.findAndModify(({ query: { milk: { $gt: <A> } }, sort: { milk: 1 }, update: { $set: { <B>: true } } }))
{ "_id" : ObjectId("5f4e50da2d4b45b7f11b6d76"), "name" : "daisy", "milk" : 6, "expected_milk" : 5 }
>> cowCol.find({"sell" : true})
{ "_id" : ObjectId("5f4e50da2d4b45b7f11b6d76"), "name" : "daisy", "milk" : 6, "expected_milk" : 5, "sell": true }
Using the shell window, change <A> to update the first document with the milk field value of 6 as the document we want to update.
Change <B> to the highlighted field name shown in the find() query below.
CRUD: MQL Exercise
>>> cowCol.updateMany({ milk: { <A>: 5 } }, { <B>: { sell: true } })
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 3 }
Using the shell window again, change <A> to the greater than operator
Change <B> to the operator we will use to set the value of the field in the documents we will update.
As we already updated one of the eligible documents, only 3 are modified.
CRUD: MQL Exercise
Quiz
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
This incorrect. The insertOne and insertMany functions do not take a filter document.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. The findAndModify function is atomic in terms of the modifications to the single document it operates upon.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. This is how these functions operate, firstly the read and then the atomic write.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. All the other functions return a document rather than a cursor.
MQL Delete
MQL Delete
Specifically the db.collection.deleteOne() and db.collection.deleteMany() methods but also db.collection.drop().
To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method
Additional methods include db.collection.findOneAndDelete() and db.collection.findAndModify(), both offer a sort option. Deletes are also possible via the db.collection.bulkWrite() method.
MQL Delete
Specifically the db.collection.deleteOne() and db.collection.deleteMany() methods but also db.collection.drop().
To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method
Additional methods include db.collection.findOneAndDelete() and db.collection.findAndModify(), both offer a sort option. Deletes are also possible via the db.collection.bulkWrite() method.
MQL Delete
Specifically the db.collection.deleteOne() and db.collection.deleteMany() methods but also db.collection.drop().
To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method
Additional methods include db.collection.findOneAndDelete() and db.collection.findAndModify(), both offer a sort option. Deletes are also possible via the db.collection.bulkWrite() method.
Quiz
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
This incorrect. Using {} or an empty document will delete all documents in the collection.
Quiz
Which of the following are true for MongoDB MQL?
This incorrect. It is possible with db.collection.findOneAndDelete() or with db.collection.findAndModify(), both offer the ability to sort order of the documents for deletion.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. All write operations in MongoDB are atomic, a delete is a write operation.
MQL Query Operators: Comparison
MQL Query Operators
Comparison
Logical
Element, Array, Evaluation, Bitwise, Comment, Geospatial, and Projection
Update and Update Modifiers
MQL Query Operators: Comparison
$lt Exists and less than
$lte: Exists and less than or equal to
$gt: Exists and greater than
$gte: Exists and greater than or equal to
$ne: Does not exist or does but not equal to
$eq: Exists and equal to
$in: Exists and in a set
$nin: Does not exist or not in a set
>>> cowCol = db.getCollection("cow")
test.cow
>>> for(c=0;c<10;c++) {
cowCol.insertOne({ name: "daisy", milk: c} )
}
{
"acknowledged" : true,
"insertedId" : ObjectId("5f2aefa8fde88235b959f0b1e")
}
>>> cowCol.find({milk:{$gt:6}})
{"_id": ObjectId("5f2aefa8fde88235b959f0b1c"), "name": "daisy", milk: 7}
{"_id": ObjectId("5f2aefa8fde88235b959f0b1d"), "name": "daisy", milk: 8}
{"_id": ObjectId("5f2aefa8fde88235b959f0b1e"), "name": "daisy", milk: 9}
MQL Operators Comparison: Example
MQL Operator Comparison: Exercise
>>> cowCol = db.getCollection("cow")
test.cow
>>> for(c=0;c<10;c++) {
cowCol.insertOne({ name: "daisy", milk: c} )
}
{
acknowledged : true,
insertedIds : ObjectId(5f2aefa8fde88235b959f0b1e),
}
Let’s insert some real data on cows!
MQL Operator Comparison: Exercise
Find the docs with the field “milk” greater than 6.
>>> cowCol.find({milk:{$gt:6}})
{ "_id": ObjectId(5f2aefa8fde88235b959f0b1c), "name" : "daisy", "milk" : 7 }
{ "_id": ObjectId(5f2aefa8fde88235b959f0b1d), "name" : "daisy", "milk" : 8 }
{ "_id": ObjectId(5f2aefa8fde88235b959f0b1e), "name" : "daisy", "milk" : 9 }
MQL Operator Comparison: Exercise
Using updateMany ( ) to update 3 documents. Using the same window, change <a> to the operator for less than or equal. Change <b> to the value necessary to find all the documents whose milk is less than or equal to 3.
>>> cowCol.find({milk:{<a>:<b>}})
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d67"), "name" : "daisy", "milk" : 0 }
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d67"), "name" : "daisy", "milk" : 1 }
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d67"), "name" : "daisy", "milk" : 2 }
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d67"), "name" : "daisy", "milk" : 3 }
MQL Query Operators Cont.
MQL Query Operators
Comparison
Logical
Element, Array, Evaluation, Bitwise, Comment, Geospatial, and Projection
Update and Update Modifiers
Diverse Search Parameters
MQL Query Operators: Logical
$or Match either of two or more values
$not Used with other operators to negate
$nor Match neither of two or more values
$and Match both of two or �more values
>>> cowCol.find({$and: [ {milk: { $gt: 6 } }, {milk: { $lt: 9 } } ] })
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d6e"), "name": "daisy", "milk": 7 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d6f"), "name": "daisy", "milk": 8 }
Logical Operator: Example One
>>> cowCol.find({milk:{$not:{$gt:6}}})
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d67"), "name": "daisy", "milk": 0 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d68"), "name": "daisy", "milk": 1 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d69"), "name": "daisy", "milk": 2 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d6a"), "name": "daisy", "milk": 3 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d6b"), "name": "daisy", "milk": 4 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d6c"), "name": "daisy", "milk": 5 }
{"_id": ObjectId("5f4e41d12d4b45b7f11b6d6d"), "name": "daisy", "milk": 6 }
Logical Operator: Example Two
MQL Query Operators
Comparison
Logical
Element, Array, Evaluation, Bitwise, Comment, Geospatial, and Projection
Update and Update Modifiers
Diverse Search Parameters
MQL Query Operators: Various categories
$exists: Match documents that have the specific field
$type: Selects documents if a field is of the specified type
$elemMatch: Selects documents if element �in the array field matches all the specified $elemMatch conditions. Limits the contents �of an <array> field from the query results �to contain only the first element matching �the conditions.
$comment: Adds a comment to a query predicate
$expr: Allows use of aggregation expressions within the query language
$geoWithin: Selects geometries within a bounding GeoJSON geometry, requires either a 2dsphere or a 2d index
$: Selects and returns first match in array that meets condition
$slice: Limits the number of elements projected from an array
MQL Query Operators: $expr
$expr Example comparing two fields in the same collection
In this example, we again use cows and milk, however we add the ‘expected_milk’ field. This field is set one above or below the ‘milk’ field, above if ‘milk’ is an odd number or below if ‘milk’ is even.
>>>cowCol = db.getCollection("cow")
Test.cow
>>> cowCol.drop()
>>> for(c=1;c<10;c++) {
a = 0
if(c%2==0) {
a = c-1
} else {
a = c+1
}
cowCol.insertOne({ name: "daisy", milk: c, expected_milk: a} )
}
>>> cowCol.find( { $expr: { $gt: [ "$milk" , "$expected_milk" ] } } ).count()
Here’s the full result for our previous example…
>>> cowCol.find({ $expr: { $gt: [ "$milk" , "$expected_milk" ] } } )
{ "_id": ObjectId(5f351f10dcb672556f30f5fa), "name" : "daisy", "milk" : 2, "expected_milk" : 1 }
{ "_id": ObjectId(5f351f10dcb672556f30f5fc), "name" : "daisy", "milk" : 4, "expected_milk" : 3 }
{ "_id": ObjectId(5f351f10dcb672556f30f5fe), "name" : "daisy", "milk" : 6, "expected_milk" : 5 }
{ "_id": ObjectId(5f351f10dcb672556f30f600), "name" : "daisy", "milk" : 8, "expected_milk" : 7 }
MQL Query Operators
Comparison
Logical
Element, Array, Evaluation, Bitwise, Comment, Geospatial, and Projection
Update and Update Modifiers
MQL Query Operators: Various Categories
$inc: Increments the specific field by the specified amount
$currentDate: Sets the field to the current date, either as a Date or as a Timestamp
$set: Sets the value of the field to the specified value
$setOnInsert: Similar to $set but only performs this when there is an insert of a new document, it won’t update existing documents if present
$rename: Changes a field’s name to the specified name
$max: Only updates the field if the value specified is greater than the existing value
$addToSet: Selects and returns first match in array that meets condition
$push: Adds an item to an array
$each: Modifies the $push and $addToSet operators to append multiple items for array updates
Query Operators: Exercise
>>> for(c=0;c<10;c++) {cowCol.insertOne({ name: "daisy", milk: c})
}
{
acknowledged : true,
insertedIds : ObjectId(5f2aefa8fde88235b959f0b1e),
}
>>> cowCol = db.getCollection("cow")
Test.cow
>>> cowCol.drop()
Find the docs where milk is greater than 8
>>> cowCol.find({milk:{$gt:8}})
{ "_id": ObjectId(5f2aefa8fde88235b959f0b1e), "name" : "daisy", "milk" : 9 }
>>> cowCol.find({milk:{$gt:8}})
{ "_id": ObjectId(5f2aefa8fde88235b959f0b1e), "name" : "rose", "milk" : 9 }
>>> cowCol.update({ milk: 9 }, { $set: { "name" : "rose" }, $setOnInsert: { milk: 10 }}, { upsert: true } );
Using updateMany() to update 3 documents
>>> cowCol.find({milk:{<a>:<b>}})
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d67"), "name" : "daisy", "milk" : 0 }
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d68"), "name" : "daisy", "milk" : 1 }
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d69"), "name" : "daisy", "milk" : 2 }
{ "_id" : ObjectId("5f4e41d12d4b45b7f11b6d6a"), "name" : "daisy", "milk" : 3 }
Using the same window, change <a> to the operator for less than or equal to.
Change <b> to the value necessary to find all the documents whose milk is less than or equal to 3.
Quiz
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
This is correct. Both the $in and the $nin functions in MQL use a set to determine the membership or not for a particular piece of data.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. The logic checks in both the $gt and the $gte will verify whether fields exceed (are greater than) the specified criteria.
Quiz
Which of the following are true for MongoDB MQL?
This incorrect. Both $eq and $ne further check for the exists or not of the specified criteria.
Quiz
Which of the following are true for MongoDB MQL?
Quiz
Which of the following are true for MongoDB MQL?
This is correct. The $and operator allows you to use two or more operators together.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. The $and operator allows you to work with multiple fields in a MQL query.
Quiz
Which of the following are true for MongoDB MQL?
This is correct. It can be nested to provide more complex logical conditions.
Quiz
Which of the following are true for MongoDB MQL?
This incorrect. $set will create new fields in single or multiple field-value pairs if they do not already exist.
Continue Learning!
GitHub Student Developer Pack
Sign up for the MongoDB Student Pack to receive $50 in Atlas credits and free certification!
MongoDB University has free self-paced courses and labs ranging from beginner to advanced levels.