MongoDB: Basic Select, Insert, Update, Delete – CRUD [Beginner Tutorial]

MongoDB is an open-source document database. Document in MongoDB means a row or record in the database. A document contains data in key-value pairs. MongoDB is popular for it’s high performance, scalability and availability.

This article shows how to perform simple select, insert, update, delete database operations in MongoDB. That’s also referred as CRUD (Create, Read, Update, Delete) operation. We will be performing these operations through terminal/command-prompt using MongoDB shell.

I assume that you have already installed MongoDB on your computer. Here’s the installation guide if your have not installed it already: MongoDB Installation

To start MongoDB server and to check the status of MongoDB server, you can run the following commands on your terminal:


sudo service mongod start
sudo service mongod status

To stop and restart MongoDB server:


sudo service mongod stop
sudo service mongod restart

Go to MongoDB shell

In your terminal/command prompt, run the command mongo:


mukesh@chapagain:~$ mongo
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
Welcome to the MongoDB shell.
For interactive help, type "help".

Show databases


> show dbs
admin  0.000GB
local  0.000GB

Create new database

use <db> is used to create new database in MongoDB if the database does not exist. It then selects/switches to that database. If the database already exists then this command will simply switch to the database.

Let’s create a new database named test.


> use test
switched to db test

db command will show the currently selected database name.


> db
test

Now, let us use show dbs command to see if it shows our newly created database or not:


> show dbs
admin  0.000GB
local  0.000GB

It is still not showing the database named test that we recently created.

Actually, to show the database, the newly created database should have some data in it.

Create Collection

MongoDB vs Relational database

Collection = Table
Document = Row
Column = Field

Let’s insert some data into our database.


> db.users.insert({"name":"Mukesh"});
WriteResult({ "nInserted" : 1 })

With the above command, MongoDB will automatically create a new collection named users and insert a document with field “name”.

In Relational database (RDBMS) terms, we call it like creating a new table “users” and inserting a row that has column named “name”.

Show collections created


> show collections
users

We can also manually create collections using command db.createCollection(name, options)


> db.createCollection('subjects')
{ "ok" : 1 }
> show collections
subjects
users

Drop database

In this example, we will create a new database, then add some data into it and finally we drop that database.


> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB

We create a new database named “hello”


> use hello
switched to db hello
> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB

Then we add a collection named “hi” to database “hello”


> db.hi.insert({"name":"mukesh chapagain"})
WriteResult({ "nInserted" : 1 })
> show collections
hi
> show dbs
admin  0.000GB
hello  0.000GB
local  0.000GB
test   0.000GB

The database is shown with “show dbs” command after adding collection to it.

To check on which database we are, we use “db” command as shown below:


> db
hello

Now, we drop the database.


> db.dropDatabase()
{ "dropped" : "hello", "ok" : 1 }
> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB

Let’s switch back to database named “test”.


> use test
switched to db test
> db
test

Drop Collection

Here, we drop a collection named subjects from database test. For this db.COLLECTION_NAME.drop() command is used.


> db
test
> show collections
subjects
users
> db.subjects.drop()
true
> show collections
users

Insert Document

db.COLLECTION_NAME.insert(document) OR db.COLLECTION_NAME.save(document) command is used to insert document data into a collection.


> db.users.insert({name: "Chapagain"})
WriteResult({ "nInserted" : 1 })

Query Document

find()</strong method is used to fetch all documents. findOne() method will fetch only one document.


> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "Mukesh" }
{ "_id" : ObjectId("5925b9faa971eb3857cf025f"), "name" : "Chapagain" }
> db.users.findOne()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "Mukesh" }

You can also use pretty() function after find() function. It will pretty print the result.

Querying document for individual name value [where name = ‘Mukesh’] [where name = ‘Chapagain’]


> db.users.find({name:"Mukesh"}).pretty()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "Mukesh" }
> db.users.find({name:"Chapagain"})
{ "_id" : ObjectId("5925b9faa971eb3857cf025f"), "name" : "Chapagain" }

Update Document

update() and save() methods can be used to update document data.

db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

Here, we update the name “Mukesh” to “PHP”:


> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "Mukesh" }
{ "_id" : ObjectId("5925b9faa971eb3857cf025f"), "name" : "Chapagain" }
> db.users.update({name:"Mukesh"},{$set:{name:"PHP"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("5925b9faa971eb3857cf025f"), "name" : "Chapagain" }

db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Here, we update data by ID value. We change the name from “Chapagain” to “Magento”.


> db.users.save({"_id" : ObjectId("5925b9faa971eb3857cf025f"), "name":"Magento"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("5925b9faa971eb3857cf025f"), "name" : "Magento" }

Delete Document

db.COLLECTION_NAME.remove({}) = Remove all documents
db.COLLECTION_NAME.remove(CRITERIA) = Remove only those documents that meet the CRITERIA specified
db.COLLECTION_NAME.remove(CRITERIA, 1) = Remove only one document that meet the CRITERIA specified

Here, we delete the document that has name “Magento”.


> db.users.remove({"name":"Magento"})
WriteResult({ "nRemoved" : 1 })
> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }

Projection

Projection in MongoDB means fetching only particular fields of a document, instead of fetching all the fields of the document. We will be using find() command with extra parameter.

db.COLLECTION_NAME.find({},{FIELD_NAME:1})

We can also set “FIELD_NAME:0” to deselect it.

Here, we deselect id and select only name field from the document.


> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
> db.users.find({},{name:1,_id:0})
{ "name" : "PHP" }

Bulk Insert

Insert more than one document at once.


> db.users.insert([{name:'Python'}, {name:'JAVA'}, {name:'SQL'}])
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 3,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})
> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("592699bba971eb3857cf026a"), "name" : "Python" }
{ "_id" : ObjectId("592699bba971eb3857cf026b"), "name" : "JAVA" }
{ "_id" : ObjectId("592699bba971eb3857cf026c"), "name" : "SQL" }

Limit & Sort

>db.COLLECTION_NAME.find().limit(NUMBER)

>db.COLLECTION_NAME.find().sort({FIELD_NAME:1})


> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("592699bba971eb3857cf026a"), "name" : "Python" }
{ "_id" : ObjectId("592699bba971eb3857cf026b"), "name" : "JAVA" }
{ "_id" : ObjectId("592699bba971eb3857cf026c"), "name" : "SQL" }
> db.users.find().limit(2)
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("592699bba971eb3857cf026a"), "name" : "Python" }
> db.users.find().sort({name:1})
{ "_id" : ObjectId("592699bba971eb3857cf026b"), "name" : "JAVA" }
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("592699bba971eb3857cf026a"), "name" : "Python" }
{ "_id" : ObjectId("592699bba971eb3857cf026c"), "name" : "SQL" }
> db.users.find().limit(2).sort({name:1})
{ "_id" : ObjectId("592699bba971eb3857cf026b"), "name" : "JAVA" }
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }

Pretty Print the Output

pretty() function makes the output more readable.


> db.users.insert({name:'Mukesh Chapagain', country:'Nepal', age:'99'})
WriteResult({ "nInserted" : 1 })
> db.users.find()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("592699bba971eb3857cf026a"), "name" : "Python" }
{ "_id" : ObjectId("592699bba971eb3857cf026b"), "name" : "JAVA" }
{ "_id" : ObjectId("592699bba971eb3857cf026c"), "name" : "SQL" }
{ "_id" : ObjectId("5926c55ba971eb3857cf026d"), "name" : "Mukesh Chapagain", "country" : "Nepal", "age" : "99" }
> db.users.find().pretty()
{ "_id" : ObjectId("5925a23fa971eb3857cf025c"), "name" : "PHP" }
{ "_id" : ObjectId("592699bba971eb3857cf026a"), "name" : "Python" }
{ "_id" : ObjectId("592699bba971eb3857cf026b"), "name" : "JAVA" }
{ "_id" : ObjectId("592699bba971eb3857cf026c"), "name" : "SQL" }
{
    "_id" : ObjectId("5926c55ba971eb3857cf026d"),
    "name" : "Mukesh Chapagain",
    "country" : "Nepal",
    "age" : "99"
}

Hope this helps. Thanks.