Removing Documents: MongoDB

Lets learn how to remove documents from the collection using remove() and drop() methods.

remove drop mongodb

test database, names collection

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
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2
}
{
        "_id" : ObjectId("53c63b26b003603dfdcf8c52"),
        "Company" : "Xiaomi",
        "Product" : "Mi3",
        "No" : 3
}
{
        "_id" : ObjectId("53c63bd1b003603dfdcf8c53"),
        "Product" : "Smart Watch",
        "No" : 4,
        "Company" : "Sony"
}

We have 4 documents in “names” collection.

remove() method, with simple condition

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
> db.names.remove({"No": 4});
WriteResult({ "nRemoved" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c63b26b003603dfdcf8c52"),
        "Company" : "Xiaomi",
        "Product" : "Mi3",
        "No" : 3,
        "IT" : "true"
}

Here the document with “No: 4” was removed from the collection.

Removing Documents: MongoDB


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

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



remove() method, with comparison condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> db.names.remove({"No": {$gt: 2}});
WriteResult({ "nRemoved" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2,
        "IT" : "true"
}

Here whatever documents which has “No” greater than 2 got removed.

remove() method to remove all documents from the collection

1
2
3
4
5
6
7
8
9
10
11
> db.names.remove({});
WriteResult({ "nRemoved" : 2 })
 
> db.names.find().pretty()
 
> show collections
names
system.indexes
 
> db.system.indexes.find().pretty()
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.names" }

If we pass empty argument to remove() method, it matches with all the documents present in the collection, hence removes all the documents one-by-one.

But it doesn’t remove the contents/documents/index present in “system.indexes” collection.

drop() method

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
> db.names.find()
 
> db.names.insert({"Company": "Apple", "Product": "iPhone", "No": 1});
WriteResult({ "nInserted" : 1 })
 
> db.names.insert({"Company": "Google", "Product": "Nexus", "No": 2});
WriteResult({ "nInserted" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6c5d95879b1ff1f0b8356"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 1
}
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
 
> db.names.drop();
true
 
> db.names.find().pretty()
 
> db.system.indexes.find().pretty()

Since “names” collection was empty, we inserted 2 documents into it. Now we applied drop() method on the collection, which drops all the document present in the collections at once. It also removes the document/index/content present inside “system.indexes” collection.

Note: If you want to remove/drop all the documents present inside the collection, make use of drop() method, as it removes all the documents at once, its more efficient than remove({}) method which removes documents one by one. Use remove() method, when you want to remove one or a set of documents from the collection.

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).

Load Data From External JavaScript File: MongoDB

This video tutorial illustrates loading data to mongoDB server from an external JavaScript file ( Writing script for MongoDB shall )

Here, we write a simple JavaScript file and using command prompt we load the contents of JavaScript file into new Database.

import-data

JavaScript file
load.js – in path: C:/temp/load.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
db.person.insert({
name:'Satish',
age:25,
skills:['nodejs', 'mongoDB', 'HTML5']
});
 
db.person.insert({
name:'Kiran',
age:27,
skills:['PHP', 'mySQL', 'HTML5']
});
 
db.person.insert({
name:'Sunitha',
age:24,
skills:['html', 'ASP']
});

Here we’re inserting some data/record/documents into the collection person.

Database’s Before running the script

1
2
3
4
5
6
7
8
9
10
11
12
13
C:\>cd mongodb
 
C:\mongodb>cd bin
 
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.3
connecting to: test
> show dbs
admin   0.203125GB
company 0.203125GB
local   0.078125GB
> exit
bye

Before running the script, we have only 3 databases.

Running the script

1
2
3
C:\mongodb\bin>mongo 127.0.0.1/satish C:/temp/load.js
MongoDB shell version: 2.4.3
connecting to: 127.0.0.1/satish

Here, mongo is the JavaScript shall.
127.0.0.1 is nothing but our localhost.
satish is the new database we are creating.
C:/temp/load.js is the path of load.js file.
We’re loading the contents of load.js file into new database satish.

Database’s After running the script

1
2
3
4
5
6
7
8
9
10
11
12
13
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.3
connecting to: test
> show dbs
admin   0.203125GB
company 0.203125GB
local   0.078125GB
satish  0.203125GB
> use satish
switched to db satish
> show collections
person
system.indexes

New database satish has been added and it has person collection, which we loaded from the JavaScript file.

Documents/records In person collection

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
> db.person.find().forEach(printjson)
{
        "_id" : ObjectId("518b62443cbad352108c321b"),
        "name" : "Satish",
        "age" : 25,
        "skills" : [
                "nodejs",
                "mongoDB",
                "HTML5"
        ]
}
{
        "_id" : ObjectId("518b62443cbad352108c321c"),
        "name" : "Kiran",
        "age" : 27,
        "skills" : [
                "PHP",
                "mySQL",
                "HTML5"
        ]
}
{
        "_id" : ObjectId("518b62443cbad352108c321d"),
        "name" : "Sunitha",
        "age" : 24,
        "skills" : [
                "html",
                "ASP"
        ]
}

Using find() method we display all its contents.

This way we could load application data from an external JavaScript file.

Writing script for MongoDB shall


[youtube https://www.youtube.com/watch?v=ygK2zE1-k0w]

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



Note:
This method will be handy while migrating our application from one mongoDB server to another mongoDB server.
There is import/export options in mongoDB, but this method is also helpful if we have some custom data to be inserted. nontheless a useful tool to have.

Create and Insert Documents: MongoDB

In this video tutorial, we’ll look at the basic differences between MongoDB and traditional Database Management Systems. Also, commands to create database, collection, documents – insertion.

Topic of discussion:
Key differences.
Keyword differences.
Schema-free collection.
Database creation.
Creation of Collection.
Insertion of Documents.
JavaScript Console/Shall.

Some Commands

Show Database Already Present

1
show dbs

Create Database

1
use company

In MongoDB, it’ll never actually create any database or collection until we start storing documents in it!

Point object ‘db’ to our new database, by switching to company database

1
2
3
4
>use company
Switched to db company 
>db
company

Naming our Collection

1
db.info

So our collection name is info

Number of documents present

1
db.info.count()

using count() method, we check the no of documents present inside info collection.

Inserting document into Collection

1
2
3
4
5
db.info.insert({
 name     : 'Apple',
 product  : 'iPhone5S',
 emp_no   : 100
});

This inserts our first record.
insert() is the method, which accepts key-value pair object as it’s parameter.

JavaScript Shall
Since, this is a JavaScript shall, we can write any valid JavaScript code and interact directly with MongoDB.

Lets see another method to insert documents into the same collection.

Using save method

1
2
3
4
5
6
7
8
9
>var data = {}
>data.name = 'Technotip IT Solutions'
>data.product = 'Video Tutorials - Educational'
>data.emp = [ 'Satish', 'Kiran' ]
>data.videos = {}
>data.videos.mongo = 'MongoDB videos'
>data.videos.php = 'PHP Video Tutorials'
 
>db.info.save(data);

We create a JSON object data.
We start storing { key: value } pair into it.
emp is an array, which contains name of 2 employees.
videos is a sub object.

Now using save method we insert this data object into info collection.

Save()
Save() is a higher lever method. It checks to see if the object we’re inserting is already present in our collection, by checking the _id value we’re inserting. _id field(which is a primary key in MongoDB document)
– If there is no matching _id field in a document, it’ll call insert method and insert the data. And if the data being entered has no _id value, insert() method will create _id value for us, and insert the data into the collection.
– If _id matches to any document in our collection, it’ll use update() instead to update the previously present data with the new data entered by the user.

Database, Collections, Documents: MongoDB


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

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



Note:
There is no Schema for our collection. i.e., no column name and datatype.
Since documents are in BSON format, insertion and finding data is much faster.

Schema-free design is flexible and is of much use in modern day web application.

Example: Users upload photos and tag names of people in the pic. This can be stored as an array of tags in a key value pair, for only those pics which has tags. For other pics, we need not create this array itself. This is flexible. Also BSON format helps create application with high Scalability.