Pluralsight Logo
Author avatar

Praveen Kumar

Author badge Author

Introduction to MongoDB - Editing Records

Praveen Kumar

Author BadgeAuthor
  • Aug 7, 2018
  • 15 Min read
  • 6,206 Views
  • Aug 7, 2018
  • 15 Min read
  • 6,206 Views
SQL
MongoDB
NoSQL

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:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
> 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" : "praveen@example.com",
    "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".

1
2
3
4
5
6
7
8
9
10
db.students.update(
  {
    name: "Baahubali"
  },
  {
    name: "Baahubali",
    degree: "Hill Climbing",
    email: "baahu@mahishmati.com"
  }
);

If we go ahead and run the above command, we get:

1
2
3
4
5
6
7
8
9
> db.students.update({
...   "name": "Baahubali"
... }, {
...   "name": "Baahubali",
...   "degree" : "Hill Climbing",
...   "email" : "baahu@mahishmati.com"
... });
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
db.students.update(
  {
    name: "Baahubali"
  },
  {
    name: "Baahubali",
    degree: "Hill Climbing",
    email: "baahu@mahishmati.com"
  },
  {
    upsert: true
  }
);

Executing the above command, we get the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> db.students.update({
...   "name": "Baahubali"
... }, {
...   "name": "Baahubali",
...   "degree" : "Hill Climbing",
...   "email" : "baahu@mahishmati.com"
... }, {
...   "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():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
> db.students.find().pretty();
{
    "_id" : ObjectId("592ebe7e8e61243307417cc4"),
    "name" : "Praveen Kumar",
    "degree" : "Cloud Computing MSc",
    "email" : "praveen@example.com",
    "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" : "purush@example.com"
}
{
    "_id" : ObjectId("592ed5818e61243307417cc6"),
    "name" : "Meaow Meaow",
    "degree" : "Cat Study",
    "email" : "meaow@example.com",
    "phone" : [
        "9850420420"
    ]
}
{
    "_id" : ObjectId("592ffa57962222f55cf0a823"),
    "name" : "Baahubali",
    "degree" : "Hill Climbing",
    "email" : "baahu@mahishmati.com"
}
>

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:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> 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" : "baahu@mahishmati.com"
}
>

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.

1
2
3
4
5
6
7
8
9
10
11
12
> 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?

1
2
3
4
5
6
7
8
9
> db.students.find();
{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing MSc", "..." ] }
{ "_id" : ObjectId("592ed5818e61243307417cc5"), "name" : "Purushothaman", "degree" : "Management", "email" : "purush@example.com" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "meaow@example.com", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "baahu@mahishmati.com" }
{ "_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:

1
2
3
db.students.remove({
  name: "Blah"
});

Firing the above command, we are left with:

1
2
3
4
5
> db.students.remove({
...   "name": "Blah"
... });
WriteResult({ "nRemoved" : 1 })
>

Nice, one record has been removed. Let's try the Bleh as well.

1
2
3
db.students.remove({
  name: "Bleh"
});

The output of the above command shows us:

1
2
3
4
5
> 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
> 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" : "praveen@example.com", "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" : "purush@example.com" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "meaow@example.com", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "baahu@mahishmati.com" }
{ "_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" : "praveen@example.com", "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" : "purush@example.com" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "meaow@example.com", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "baahu@mahishmati.com" }
{ "_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.

1
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:

1
2
3
db.students.find({
  $or: [{ name: "Blah" }, { name: "Bleh" }]
});

Woohoo! Executing the above code, we get both the records now.

1
2
3
4
> 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.

1
2
3
4
5
6
7
8
> 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" : "praveen@example.com", "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" : "purush@example.com" }
{ "_id" : ObjectId("592ed5818e61243307417cc6"), "name" : "Meaow Meaow", "degree" : "Cat Study", "email" : "meaow@example.com", "phone" : [ "9850420420" ] }
{ "_id" : ObjectId("592ffa57962222f55cf0a823"), "name" : "Baahubali", "degree" : "Hill Climbing", "pigeon" : "baahu@mahishmati.com" }
>

Sweet! That works.

Additional Reading

Please continue on to the next guide in this series for more information on MongoDB - Operators.

0