Introduction to MongoDB - Editing Records
In this guide, we will introduce MongoDB and how to get started with using it. By the end of this series of guides, you will understand everything up to the basic CRUD (Create, Retrieve, Update, Delete) operations. Learn today!
Jan 10, 2019 • 15 Minute Read
Getting Set Up
Please read the first guide in this series for more information about MongoDB - Installation, Shell, and Database Management.
Removing Fields
You can remove all or few fields from a single record. That's how NoSQL works. For this, we will be using a function called $unset, which is opposite to the $set, which we saw before.
The syntax for this is quite tricky. You need to pass the whole object as the second parameter. For example, let's say I don't want that points field now. Instead I want to remove the points category from my record. With NoSQL, I just need to execute the following command:
db.students.update(
{
name: "Praveen Kumar"
},
{
$unset: {
points: ""
}
}
);
Here, you can see that it follows the similar structure to $inc and $set. Only thing is that you can give any value for the field. Giving "" or 75 works. Upon executing this, we have the following output:
> db.students.update({
... "name": "Praveen Kumar"
... }, {
... $unset: {
... "points" : ""
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.students.find({"phone": "9840035007"}).pretty();
{
"_id" : ObjectId("592ebe7e8e61243307417cc4"),
"name" : "Praveen Kumar",
"degree" : "Cloud Computing MSc",
"email" : "[email protected]",
"subjects" : [
{
"name" : "Internet Networks",
"prof" : "Prof. Awesome Blossom"
},
{
"name" : "Cloud Computing",
"prof" : "Prof. Tech Ninja"
},
{
"name" : "Web Development",
"prof" : "Prof. Chunky Monkey"
}
],
"phone" : [
"9840035007",
"9967728336",
"7772844242"
]
}
>
Yippee! We have removed points from my record.
Upsertion
Upsert is a new term here and it's a combination of update and insert. Upserting is similar to saying, "if a record is present, update it, otherwise, insert it." An upsertion occurs when you try to find a match in the database, can't find it, and insert a vlaue instead of simply returning. Let's consider the same example, where we have three records and we'll try to update a non-existent record, say the student "Baahubali".
db.students.update(
{
name: "Baahubali"
},
{
name: "Baahubali",
degree: "Hill Climbing",
email: "[email protected]"
}
);
If we go ahead and run the above command, we get:
> db.students.update({
... "name": "Baahubali"
... }, {
... "name": "Baahubali",
... "degree" : "Hill Climbing",
... "email" : "[email protected]"
... });
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
>
The result is 0 all across. Doing a simple find() will give the same results as they were before. If we want the database to check if the match is not found, then insert it, we need to use the option called upsert. Now let's use the same query and make a small change in it. Let's add a third parameter for the update() function, specifying an object with only upsert set to true.
db.students.update(
{
name: "Baahubali"
},
{
name: "Baahubali",
degree: "Hill Climbing",
email: "[email protected]"
},
{
upsert: true
}
);
Executing the above command, we get the following:
> db.students.update({
... "name": "Baahubali"
... }, {
... "name": "Baahubali",
... "degree" : "Hill Climbing",
... "email" : "[email protected]"
... }, {
... "upsert": true
... });
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("592ffa57962222f55cf0a823")
})
>
By setting the upsert parameter to true, we can see there's one record inserted (actually upserted) with the _id returned to us. This is similar to the MySQL Insert query on a table where there is AUTO_INCREMENT set. Now let's see what's there in the database by making a find():
> db.students.find().pretty();
{
"_id" : ObjectId("592ebe7e8e61243307417cc4"),
"name" : "Praveen Kumar",
"degree" : "Cloud Computing MSc",
"email" : "[email protected]",
"subjects" : [
{
"name" : "Internet Networks",
"prof" : "Prof. Awesome Blossom"
},
{
"name" : "Cloud Computing",
"prof" : "Prof. Tech Ninja"
},
{
"name" : "Web Development",
"prof" : "Prof. Chunky Monkey"
}
],
"phone" : [
"9840035007",
"9967728336",
"7772844242"
]
}
{
"_id" : ObjectId("592ed5818e61243307417cc5"),
"name" : "Purushothaman",
"degree" : "Management",
"email" : "[email protected]"
}
{
"_id" : ObjectId("592ed5818e61243307417cc6"),
"name" : "Meaow Meaow",
"degree" : "Cat Study",
"email" : "[email protected]",
"phone" : [
"9850420420"
]
}
{
"_id" : ObjectId("592ffa57962222f55cf0a823"),
"name" : "Baahubali",
"degree" : "Hill Climbing",
"email" : "[email protected]"
}
>
Yay! Now Baahubali is in our list of students. (Let's hunt for Kalakeya now! 😁)
Clearly, upsert is a useful function that can save quite a bit of error handling and time down the line.
Renaming Fields
We have Baahubali as our student, but wait. In those Mahishmati times, they didn't have email, did they? Let's replace his email field with pigeon. We have a quick stuff for renaming things in MongoDB. As you guessed, the operator is $rename. This function is also similar to our $set function in its syntax, so to rename, it would be:
db.students.update(
{
name: "Baahubali"
},
{
$rename: {
email: "pigeon"
}
}
);
Now when we execute the above command and do a find() and see the results, we get:
> db.students.update({
... "name": "Baahubali"
... }, {
... $rename: {
... "email" : "pigeon"
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.students.find({"name": "Baahubali"}).pretty();
{
"_id" : ObjectId("592ffa57962222f55cf0a823"),
"name" : "Baahubali",
"degree" : "Hill Climbing",
"pigeon" : "[email protected]"
}
>
Ah! I love this pigeon stuff. We have got one record matched and modified. We have now successfully changed the email to pigeon for Baahubali.
Note to PETA: No pigeons were hurt while writing this article.
Removing Records
We are in the final part of the CRUD (Create Retrieve Update Delete) operation. Make sure that you understand each of the other letters before moving onto deletion.
Deleting records or removing documents is easier as well. We will be using the remove() function for the removal operation. The function is similar to update(), but it doesn't take any other parameters except the options (optional) with justOne (we will talk about it sooner). Let's try adding a dumb record before trying to delete any of our students.
> db.students.insert([{"name": "Bleh"}, {"name": "Bleh"}, {"name": "Blah"}]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
Yep, now we have these Blah and two Bleh students, who just have their names in them. Let's check the list of students quickly?
> db.students.find();
{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing MSc", "..." ] }
{ "_id" : ObjectId("592ed5818e61243307417cc5"), "name" : "Purushothaman", "degree" : "Management", "email" : "[email protected]" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "[email protected]", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "[email protected]" }
{ "_id" : ObjectId("59300e628e61243307417cc9"), "name" : "Bleh" }
{ "_id" : ObjectId("59300e628e61243307417cca"), "name" : "Bleh" }
{ "_id" : ObjectId("59300e628e61243307417ccb"), "name" : "Blah" }
>
Oh yes. We have three USOs (Unidentified Student Objects). Let's perform a little cleanup now. The syntax for calling the remove function would be something like this:
db.students.remove({
name: "Blah"
});
Firing the above command, we are left with:
> db.students.remove({
... "name": "Blah"
... });
WriteResult({ "nRemoved" : 1 })
>
Nice, one record has been removed. Let's try the Bleh as well.
db.students.remove({
name: "Bleh"
});
The output of the above command shows us:
> db.students.remove({
... "name": "Bleh"
... });
WriteResult({ "nRemoved" : 2 })
>
However, it removed all the matches. While right now removing all matches is completely safe, as we know that the Blehs are not supposed to be in our list, removing everything can be a problem if we need to check some stuff and remove one entry.
Luckily MongoDB provides a way: the justOne option. justOne does the exact thing that we want it to do right now:
justOne boolean (optional)
To limit the deletion to just one document, set to true. Omit to use the default value of false and delete all documents matching the deletion criteria.
Let's add two more Blehs as before and we'll try this justOne:
> db.students.insert([{"name": "Bleh"}, {"name": "Bleh"}]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.students.find();
{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing MSc", "email" : "[email protected]", "subjects" : [ { "name" : "Internet Networks", "prof" : "Prof. Awesome Blossom" }, { "name" : "Cloud Computing", "prof" : "Prof. Tech Ninja" }, { "name" : "Web Development", "prof" : "Prof. Chunky Monkey" } ], "phone" : [ "9840035007", "9967728336", "7772844242" ] }
{ "_id" : ObjectId("592ed5818e61243307417cc5"), "name" : "Purushothaman", "degree" : "Management", "email" : "[email protected]" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "[email protected]", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "[email protected]" }
{ "_id" : ObjectId("5930132a8e61243307417ccc"), "name" : "Bleh" }
{ "_id" : ObjectId("5930132a8e61243307417ccd"), "name" : "Bleh" }
> db.students.remove({
... "name": "Bleh"
... }, {
... "justOne": true
... });
WriteResult({ "nRemoved" : 1 })
> db.students.find();
{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing MSc", "email" : "[email protected]", "subjects" : [ { "name" : "Internet Networks", "prof" : "Prof. Awesome Blossom" }, { "name" : "Cloud Computing", "prof" : "Prof. Tech Ninja" }, { "name" : "Web Development", "prof" : "Prof. Chunky Monkey" } ], "phone" : [ "9840035007", "9967728336", "7772844242" ] }
{ "_id" : ObjectId("592ed5818e61243307417cc5"), "name" : "Purushothaman", "degree" : "Management", "email" : "[email protected]" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "[email protected]", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "[email protected]" }
{ "_id" : ObjectId("5930132a8e61243307417ccd"), "name" : "Bleh" }
>
What just happened? We inserted two students, both with the same name ("Bleh") to our database. We checked that insertion occurred using find(). Then we used remove() with the justOne attribute to remove a single element with the desired attribute ("name": "Bleh").
Thus, the option justOne helps us to check if we are removing the correct way by limiting to just one of the matched documents.
Querying with Multiple Conditions
All this time we have been limited to single-condition querying. What if we need to use multiple conditions? For example, can Bleh and Blah be removed in a single command? Well, yes! You have the mighty $or operator. Let's see how it works by querying stuff.
db.students.insert([{ name: "Bleh" }, { name: "Blah" }]);
The above command has inserted two different documents, with different name. Let's try to get both of them by using $or operator. In our find() method, we need to pass the $or as an option and add the different objects to be matched as an array:
db.students.find({
$or: [{ name: "Blah" }, { name: "Bleh" }]
});
Woohoo! Executing the above code, we get both the records now.
> db.students.find({$or: [{"name": "Blah"}, {"name": "Bleh"}]});
{ "_id" : ObjectId("593028b68e61243307417cd0"), "name" : "Bleh" }
{ "_id" : ObjectId("593028b68e61243307417cd1"), "name" : "Blah" }
>
The next thing is that, we can send this to the remove function as well and get all our dirt cleared.
> db.students.remove({$or: [{"name": "Blah"}, {"name": "Bleh"}]});
WriteResult({ "nRemoved" : 2 })
> db.students.find();
{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing MSc", "email" : "[email protected]", "subjects" : [ { "name" : "Internet Networks", "prof" : "Prof. Awesome Blossom" }, { "name" : "Cloud Computing", "prof" : "Prof. Tech Ninja" }, { "name" : "Web Development", "prof" : "Prof. Chunky Monkey" } ], "phone" : [ "9840035007", "9967728336", "7772844242" ] }
{ "_id" : ObjectId("592ed5818e61243307417cc5"), "name" : "Purushothaman", "degree" : "Management", "email" : "[email protected]" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "[email protected]", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "[email protected]" }
>
Sweet! That works.
Additional Reading
Please continue on to the next guide in this series for more information on MongoDB - Operators.