CRUD operations in MongoDB

CRUD operations in MongoDB

Abhay 6 min read

The acronym CRUD stands for Create, Read, Update, and Delete. In this section, we will learn basic CRUD operations. CRUD operations can be extremely complex sometimes, but we will not go into the complicated stuff for two reasons. First, it is not under the scope of this post. Second, we will be doing a lot of CRUD operations in the following posts.

Before we start learning CRUD, I must tell you that we will be using the mongo shell for CRUD in the following sections.

Create or insert a document

Data can be added to MongoDB in the form of documents. To add a document, we use the insert() function. We pass the document to be inserted into the insert() function. Let’s see an example –

use mydb
db.clients.insert({ "name" : "John Doe" })

The above example will insert a new document in the ‘clients’ collection. To see the document we just inserted, you can use find() like this –

use mydb
db.clients.find()
{
    "_id" : ObjectId("5411fa20f7983ae1ced3da66"),
    "name" : "John Doe"
}

If the document is inserted properly, then you will see the inserted document in your shell. MongoDB automatically inserts the _id field. MongoDB does that automatically for you if the _id field doesn’t exist. The value of the _id field is of ObjectId class. You can refer to the section on data types to learn more about ObjectId. MongoDB gives you the freedom to assign _id whatever value you want. If you have already assigned a value to _id, MongoDB will use it.

Batch insert

There are times when you would want to add more than one document. You can go ahead and make multiple insert queries, but MongoDB gives you a faster way to handle multiple insert operations. It’s called a batch insert. For the batch insert, you pass an array of documents to batchInsert() function. Let’s see an example –

> use mydb
db.clients.batchInsert( [ { 'name' : 'Mike' }, { 'name' : 'Lucy' }, { 'name' : 'Scott' } ] )

Batch inserting three documents may not make a huge difference but think about a situation where you can batch insert thousands of documents. In that case, the difference is significant and that is the situation when batch insert saves time.

Remove or Delete

Removing data is pretty straightforward. The method name is remove(), and it takes one optional argument, i.e., remove criteria. If no argument is given, then it will remove all documents existing in the collection. Of course, that logical and expected, right? If you want to remove some specific kind of documents, then you need to tell remove() function the matching criteria. Let’s see an example –

use mydb
db.clients.remove()

The above query will remove all documents in the clients collection. Though, removing all documents by remove() function would be slow. A better and faster way to remove all the documents in a collection is to drop the collection.

use mydb
db.clients.drop()

Let’s see how to remove documents that match certain criteria.

use mydb
db.clients.remove({ 'name' : 'John Doe' })

This will remove all documents where the name is John Doe.

Read or Retrieve

Retrieving data from the database is a common task. In MongoDB, it is performed using the find method. The find method takes two arguments, i.e., query criteria and projection criteria. Find will return the documents that match query criteria. Projection criteria, if provided, specifies which keys are to be returned. The find method is extremely useful and is used in different ways for different purposes. Here in this section, we will be learning only the more common usage. For details, check out mongodb documentation here.

Fetch all the documents in a collection. Both the commands will match all the documents in the clients collection. The results will be shown in batches.

db.clients.find() db.clients.find({})

To find documents where ‘name’ is ‘John Doe’.

db.clients.find({ 'name' : 'John Doe' })

To find documents where ‘name’ is ‘John Doe’ but get only ‘name’ and ‘age’ fields.

db.clients.find({ 'name' : 'John Doe' }, { 'name' : 1, 'age' : 1 })

To find documents where ‘name’ is ‘John Doe’ AND ‘age’ is 25.

db.clients.find({ 'name' : 'John Doe', 'age' : 25 })

To find documents where ‘age’ > 25.

db.clients.find({ 'age' : { '$gt' : 25 } })

To find documents where ‘age’ < 35.

db.find({ 'age' : { '$lt' : 35 } })

To find documents where the ‘age’ is between 25 and 35.

db.clients.find({ 'age' : { '$gte' : 25, '$lte' : 35 } })

To find documents where the given regular expression matches.

db.clients.find({ 'name' : /John/i })

A lot of other kinds of find queries are there. I would recommend you to go through the documentation link provided above.

Update

Modifications to documents in MongoDB are done with the update method. The update method takes two arguments. An optional third argument can also be passed for extra options. The first argument tells which documents are to be modified, and the second argument tells what to modify.

Before I give you examples, let me give you a sample document on which we will perform example updates. Here it is –

{
   'name' : 'John Doe',
   'age' : 25,
   'address' : {
       'house' : 'A – 45',
       'street' : 'North Avenue',
       'city' : 'New York',
       'country' : 'usa'
    },
   'interests' : [ 'reading', 'travelling', 'movies']
}

Change the whole document to { 'name' : 'Mike' } where ‘name’ is ‘John Doe’.

db.clients.find({ 'name' : 'John Doe' }, { 'name' : 'Mike' })

Change the ‘age’ to 35 where ‘name’ is ‘John Doe’. $set sets the value of a field. If the field doesn’t exist, $set will create the field.

db.clients.find({ 'name' : 'John Doe' }, { '$set' : { 'age' : 35 } })

Add a new Boolean field ‘married’ where ‘name’ is ‘John Doe’.

db.clients.find({ 'name' : 'John Doe' }, { '$set' : { 'married' : false } })

Add a new item ‘driving’ to interests where ‘country’ is ‘usa’.

db.clients.find({ 'address.country' : 'usa' }, { '$push' : { 'interests' : 'driving' } })

Remove ‘married’ field where ‘name’ is ‘John Doe’. Suppose you don’t want this field.

db.clients.find({ 'name' : 'John Doe' }, { '$unset' : { 'married' : 1 } })

Change ‘age’ to 40 where ‘name’ is ‘John Doe’. Also, insert a new document with ‘age’ equals 40 if no match is found. This can be achieved by passing an optional third argument (upsert) to the update method.

db.clients.find({ 'name' : 'John Doe' }, { '$set' : { 'age' : 40 } }, { upsert : true })

Change ‘city’ to ‘Chicago’ where ‘name’ is ‘John Doe’. Also, update all the documents if more than one match is found. You can pass an optional third argument (multi) to the update method to achieve this.

db.clients.find({ 'name' : 'John Doe' }, { '$set' : { 'address.city' : 'Chicago' } }, { multi : true })

The above are more common examples of an update operation. These examples are intended to give you an overview of update operations in MongoDB. I would highly recommend you to go through the documentation a few times. You can find the documentation for the update method here.