Update with UNSET Operator: MongoDB

Lets use $unset operator along with update() method, to update the documents.

update with set operator mongodb Update with UNSET Operator: MongoDB

test database, names collection

1
2
3
4
5
6
7
8
9
10
11
12
13
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Here we have 2 documents with fields _id, Company, Product and No.

Update with UNSET Operator: MongoDB


[youtube https://www.youtube.com/watch?v=8UUdITiZ5ZE]

YouTube Link: https://www.youtube.com/watch?v=8UUdITiZ5ZE [Watch the Video In Full Screen.]



We could remove a field using update() method, by not specifying it in the second argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.names.update({"No": 1}, {"Company": "Google", "No": 1});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Related Read: Update Method: MongoDB

This way, we could eliminate the field Product. But this is a tedious process – we need to remember all the fields inorder to achieve this. It gets difficult when we have many fields in our document. To solve this problem, we have $unset operator, where we only need to know the field name which we want to remove.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.names.update({"No": 1}, {$unset: {"Product": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

$unset operator syntax is same to unset or remove array from a document.

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
> db.names.update({"No": 1}, {$set: {"Product": ["LG", "Samsung", "HTC"]}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1,
        "Product" : [
                "LG",
                "Samsung",
                "HTC"
        ]
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}
 
> db.names.update({"No": 1}, {$unset: {"Product": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Related Read: Update with SET Operator: MongoDB

Update with SET Operator: MongoDB

Lets use $set operator along with update() method, to update the documents.

test database, names collection

1
2
3
> db.names.find()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }

update-with-set-operator-mongodb

Related Read: Update Method: MongoDB

Lets update the first document using only update method.

1
2
3
4
5
6
7
8
9
10
> db.names.update({"name": "Alia"}, {"name": "Alia", "age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{
        "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"),
        "name" : "Alia",
        "age" : 25
}

Everything is ok in this case. But what if you forget to mention the name field in the second argument of update() method.

1
2
3
4
5
6
> db.names.update({"name": "Alia"}, {"age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }

In this case, the name field gets erased. As we did not specify name field in the second parameter of update() method.

Using $set operator

1
2
3
4
5
6
7
8
9
10
> db.names.update({"name": "Bebo"}, {$set: {"age": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 25
}

Here we make use of document with name as Bebo. Using $set operator we only specify the fields we want to add or update. Need not specify other existing fields in order to retain them.

Update with SET Operator: MongoDB


[youtube https://www.youtube.com/watch?v=nsDnZcstUV4]

YouTube Link: https://www.youtube.com/watch?v=nsDnZcstUV4 [Watch the Video In Full Screen.]



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
> db.names.update({"name": "Bebo"}, {$set: {"age": 25, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 25,
        "salary" : 25
}
 
 
> db.names.update({"name": "Bebo"}, {$set: {"age": 26, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 26,
        "salary" : 25
}
 
 
> db.names.update({"name": "Bebo"}, {$set: {"salary": 30}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 26,
        "salary" : 30
}

We can update existing field or add a field to the existing document using $set operator and need not to worry about the other fields in the document.

Update Method: MongoDB

Lets learn how to update MongoDB document using update() method.

test database, names collection

1
2
3
4
5
6
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 27
}

Observe the document, with fields name and age. We’ll be illustrating update() method by working on this document.

update-method-mongodb

1
2
3
4
5
> db.names.update({"name": "Satish"}, {"age": 28});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"), "age" : 28 }

update() method takes at least 2 arguments. First argument being the condition(WHERE clause in sql) and the second argument being the fields to be updated. Observe that, whatever the fields we specify in the second argument are only retained(along with _id), all other fields will be erased.

1
2
3
4
5
6
7
8
9
> db.names.update({"age": 28}, {"name": "Satish", "age": 28});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 28
}

Now we’ve updated with name as well as age field and it reflects in the document in the collection.

Update Method: MongoDB


[youtube https://www.youtube.com/watch?v=6LfvsoqRoP8]

YouTube Link: https://www.youtube.com/watch?v=6LfvsoqRoP8 [Watch the Video In Full Screen.]



1
2
3
4
5
6
7
8
9
10
> db.names.update({"age": 28}, {"name": "Satish", "age": 28, "salary": 200000});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 28,
        "salary" : 200000
}

If we want to update/add a new field to the document, we must also specify all other fields we want to retain in the document.

1
2
3
4
5
> db.names.update({"age": 28}, {"salary": 300000});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"), "salary" : 300000 }

If we forget to specify other fields, then they will be erased(except _id field).

Count Method: MongoDB

Let’s learn to use count() method in MongoDB.

Count method outputs numeric value of the number of documents retrieved.

count-method-mongodb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> use test
switched to db test
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }
> db.names.count();
9
> db.names.count({"name": {$type: 2}});
8
> db.names.count({"name": {$type: 1}});
1
> db.names.count({"name": {$regex: "e"}});
3

We have 9 documents, out of which 8 documents have string values as name and 1 document has numeric value as it’s name.

Count Method: MongoDB


[youtube https://www.youtube.com/watch?v=1Cx0KT43xlw]

YouTube Link: https://www.youtube.com/watch?v=1Cx0KT43xlw [Watch the Video In Full Screen.]



Related Read: $exists, $type, $regex operators: MongoDB

$type: 2, represents string value in BSON specification. And we have 8 documents with string value for the name field.

$type: 1, represents double value in BSON specification. And we have 1 document with numeric value for the name field.

$regex: “e”, we have 3 documents which has small letter e in the string value for name field.

Note: We can make use of count() method, when we want to show the number of friends or followers each member has. So MongoDB makes it easy by facilitating developers with count() method.

SELECT / LIST Records From Database Table: PHP & MySQL
In sql, we have SELECT count(*) FROM table_name;

Cursor Object: MongoDB

Lets have a deeper look into the MongoDB cursor object.

cursor-object-mongodb

Documents in our collection
test database, names collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> use test
switched to db test
> show collections
names
system.indexes
> db.names.find();
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

We have 8 documents with name in alphabetical order, and 1 document with name as 25. So in total we have 9 documents in our names collection.

Establishing Cursor

1
2
3
4
5
6
7
8
9
10
11
12
> var cur = db.names.find();
 
> cur
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

Look at the contents of our cursor object cur.

hasNext() and next() methods on Cursor

1
2
3
4
5
6
7
8
9
> var cur = db.names.find();
> cur.hasNext();
true
> cur.next()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
> cur.next()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
> cur.next()
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }

If there are any documents to iterate inside cursor object, then hasNext() will return true orelse it’ll return false. If hasNext() returns true, then we can iterate through the documents using next() method on the cursor object.

sort() method on Cursor Object

1
2
3
4
5
6
7
8
9
10
11
12
> var cur = db.names.find();
 
> cur.sort({"name": -1});
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

We could modify the cursor object using methods like sort(), limit() and skip(). In above example, we are modifying cursor object using sort() method, and we are sorting it in reverse lexicographical order on the name field.

limit() method on Cursor Object

1
2
3
4
5
> var cur = db.names.find();
> cur.limit(3);
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }

We could limit the output/result using limit() method.

Chaining method on Cursor Object

1
2
3
4
5
6
7
8
> var cur = db.names.find();
 
> cur.sort({"name": -1}).limit(5).skip(2);
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }

Here we chain the methods sort(), limit() and skip(). We are sorting in reverse lexicographical order on the name field, then skipping the first 2 documents and then limiting the result/output to 5 documents.

The order in which these 3 methods are applied are: First sort, then skip and then limit.
Also note that, these methods modify cursor object at the server side and not on client site.

Cursor Object: MongoDB


[youtube https://www.youtube.com/watch?v=_LexQW0vSlQ]

YouTube Link: https://www.youtube.com/watch?v=_LexQW0vSlQ [Watch the Video In Full Screen.]



explain() method on Cursor Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> db.names.find().explain();
{
        "cursor" : "BasicCursor",
        "isMultiKey" : false,
        "n" : 9,
        "nscannedObjects" : 9,
        "nscanned" : 9,
        "nscannedObjectsAllPlans" : 9,
        "nscannedAllPlans" : 9,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "server" : "PC:27017",
        "filterSet" : false
}

explain() method shows that find() returns a basic cursor. More on explain() method in coming videos.

Programmatic way of printing Cursor Object content

1
2
3
4
5
6
7
8
9
10
11
12
> var cur = db.names.find();
 
> while(cur.hasNext()) printjson(cur.next());
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

While loop executes until cur.hasNext() returns true. Until cur.hasNext() is true, cur.next() keeps printing next document in the cursor cur.