How to Use Advanced Queries in MongoDB
Introduction
When you’re working with data that’s stored in MongoDB, there are times when the task at hand is more complex and you need to perform advanced queries. Fortunately, MongoDB offers a variety of methods and operators to get the job done. In this article, we’ll show you several examples of how to use advanced queries in MongoDB.
Prerequisite
In order to follow along with the examples in this tutorial, you’ll need to have MongoDB installed and configured on your machine.
Create MongoDB Sample Dataset
In this section, we’ll create a sample dataset that we can use throughout this tutorial. To follow along and create your own dataset, first connect to your Mongo shell. Then, you’ll need to perform the following steps:
1 2 | > use studentdb switched to db studentdb |
The command shown above uses the studentdb
as our database. This database will be created once we create a collection.
The following code will create a collection named student
and will insert multiple documents into it:
1 2 3 4 5 6 7 | db.student.insertMany([ { name : "John Bennet", age : 16, course : "Business Management", email : "john@example.com" }, { name : "Drew Scarlet", age : 17, course : "Information Technology", email : "drew@example.com" }, { name : "James Hampsheire", age : 16, course : "Information Technology", email : "james@example.com" }, { name : "Dale Duke", age : 18, course : "Tourism", email : "dale@example.com" }, { name : "Russel Brooke", age : 17, course : "Software Engineer", email : "rommel@example.com" } ]); |
We’ll see this notification after the above query executes successfully:
1 2 3 4 5 6 7 8 9 10 | { "acknowledged" : true, "insertedIds" : [ ObjectId("5e1a890870be6e1146e53526"), ObjectId("5e1a890870be6e1146e53527"), ObjectId("5e1a890870be6e1146e53528"), ObjectId("5e1a890870be6e1146e53529"), ObjectId("5e1a890870be6e1146e5352a") ] } |
We can verify that our insert operation was successful using the following command: db.student.find();
The output should look something like this:
1 2 3 4 5 6 7 8 9 10 11 | { "_id" : ObjectId("5e1a890870be6e1146e53521"), "name" : "John Bennet", "age" : 16, "course" : "Business Management", "email" : "john@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53522"), "name" : "Drew Scarlet", "age" : 17, "course" : "Information Technology", "email" : "drew@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53523"), "name" : "James Hampsheire", "age" : 16, "course" : "Information Technology", "email" : "james@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53524"), "name" : "Dale Duke", "age" : 18, "course" : "Tourism", "email" : "dale@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53525"), "name" : "Russel Brooke", "age" : 17, "course" : "Software Engineer", "email" : "rommel@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53526"), "name" : "John Bennet", "age" : 16, "course" : "Business Management", "email" : "john@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53527"), "name" : "Drew Scarlet", "age" : 17, "course" : "Information Technology", "email" : "drew@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53528"), "name" : "James Hampsheire", "age" : 16, "course" : "Information Technology", "email" : "james@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e53529"), "name" : "Dale Duke", "age" : 18, "course" : "Tourism", "email" : "dale@example.com" } { "_id" : ObjectId("5e1a890870be6e1146e5352a"), "name" : "Russel Brooke", "age" : 17, "course" : "Software Engineer", "email" : "rommel@example.com" } > |
Advanced Query in MongoDB Example
Now that we’ve set up our sample dataset, let’s look at some examples of how to use advanced queries in MongoDB.
Query UPDATE for MongoDB
In our first examples, we’ll show you various queries that can be performed on a MongoDB document using the update()
method.
SET FIELDS IN DOCUMENT
The following query will set the field age
with a new value of ’17’:
1 | db.student.update( { _id:ObjectId("5e1a890870be6e1146e53524") }, { $set: { "age": 17 } } ); |
The output should look something like this:
1 | WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 }) |
We can confirm that our update operation was successful using the following command: db.student.find({_id:ObjectId("5e1a890870be6e1146e53524")});
The find()
method should return something like the following:
1 | { "_id" : ObjectId("5e1a890870be6e1146e53524"), "name" : "Dale Duke", "age" : 17, "course" : "Tourism", "email" : "dale@example.com" } |
PUSH ARRAYS IN DOCUMENT
The $push
operator will push a field or an array into an existing document:
1 2 3 4 5 6 7 | db.student.update({ _id:ObjectId("5e1a890870be6e1146e53524") }, { $push: { subjects: { $each: [ "math", "science", "physical education" ] } } }); |
The above code will push, or append, an array named subject
. The array will contain the elements math
, science
and physical education
.
The result should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | db.student.find({_id:ObjectId("5e1a890870be6e1146e53524")}).pretty(); { "_id" : ObjectId("5e1a890870be6e1146e53524"), "name" : "Dale Duke", "age" : 17, "course" : "Tourism", "email" : "dale@example.com", "subjects" : [ "math", "science", "physical education" ] } |
REMOVE FIELDS IN ARRAYS
The $pop
operator is used to remove the first or the last element of an array. We use negative values to remove the first element and non-negative numbers to remove the last element in an array.
1 | db.student.update( { _id: ObjectId("5e1a890870be6e1146e53524")}, { $pop: { subjects: -1 } } ); |
The code shown above will remove the first element in the array subjects
.
The output should look like this:
1 2 3 4 5 6 7 8 9 10 11 | { "_id" : ObjectId("5e1a890870be6e1146e53524"), "name" : "Dale Duke", "age" : 17, "course" : "Tourism", "email" : "dale@example.com", "subjects" : [ "science", "physical education" ] } |
Conclusion
When you need to update documents or manipulate arrays in MongoDB, you can end up performing some complex queries and operations. In this article, we demonstrated how to use advanced queries in MongoDB, with examples featuring several different methods and operators. With these examples to guide you, you’ll be able to execute advanced queries in your own MongoDB environment.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started