MongoDB CRUD operations in detail

In the previous post, we discussed the fundamentals of MongoDB and also introduced you to MongoDB CRUD operations. In this post we will deep dive into CRUD operations as often we use them only.

Here is the list of methods provided by MongoDB to fulfill the requirement of CRUD operations.

InsertFindUpdateDelete
insertOne()findOne()updateOne()deleteOne()
insertMany()find()UpdateMany()deleteMany()
insert()findAndModify()Update()remove()
findOneAndDelete()replaceOne()
findOneAndReplace()
findOneAndUpdate()

Let’s move further and discuss each of the methods in detail.

Create

The first operation of CRUD used to create new documents in a collection. As shown in the above table MongoDB offers three methods to create new documents. These three methods use the default write concern unless we pass a write concern and likewise the use database command it also creates a new collection if the collection is not available.

db.collection.insertOne() inserts a single document into a collection.

Syntax:

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

Returns: A document containing:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.
  • A field inserted Id with the _id value of the inserted document.

In the below example we will insert a new document in userinfo collection. Make sure you are in the correct database. To use a database just write

use this command does two things, one creates a new database if it does not exist, and switch to the given database.

use user
switched to db user
db.userinfo.insertOne({name:'user 1',email:'user1@test.com',age:21})

#Output 
{
"acknowledged" : true,
"insertedId" : ObjectId("5ed6f5a9b66c8269070b4af2")
}

db.collection.insertMany() can insert multiple documents into a collection. This method takes an array of documents.

Syntax:

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

The ordered boolean parameter is Optional also as mentioned above it uses default concern if not provided. A boolean specifying whether the mongo instance should perform an ordered or unordered insert. Defaults to true.

Returns: A document containing:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled
  • An array of _id for each successfully inserted documents

Refer to the below snippet here we have created 3 documents using insert many.

db.userinfo.insertMany([

{name:'user 2',email:'user2@test.com',age:22},

{name:'user 3',email:'user3@test.com',age:32},

{name:'usr 4',email:'user4@test.com',age:30}

])

#Output 

{


"acknowledged" : true,
"insertedIds" : [
ObjectId("5ed6f6ceb66c8269070b4af3"),
ObjectId("5ed6f6ceb66c8269070b4af4"),
ObjectId("5ed6f6ceb66c8269070b4af5")
]
}

db.collection.insert() Inserts a document or documents into a collection. It works as insertOne () in case of a single document and in case of multiple documents works as insertMany ().

Syntax:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Returns:

  • A WriteResult object for single inserts.
  • A BulkWriteResult object for bulk inserts.

MongoDB also provide  db.collection.save() method to create documents but as per the Mongo documentation it is deprecated and they emphasize on using inserOne (), insertMany() and insert() methods.

Read

The second operation of CRUD used to read/fetch the documents from a collection. As shown in the above table MongoDB offers two methods to fetch the data from a collection.

db.collection.findOne() Returns one document that satisfies the specified query criteria on the collection or the first document from the collections if no query provided.

Syntax:

db.collection.findOne(query, projection)

Parameter

query:  The query parameter is an Optional document, which specifies a query for selection criteria using query operators.

projection: It is also an Optional document, which specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document. For details, see Projection.

Note: The basic thumb rule for applying projection is to use 1 to include any field and 0 to exclude. By default, the _id field is always included unless you explicitly exclude it.

Returns:

It returns One document that matches the criteria specified in the query, the first parameter. If you specify a projection parameter, findOne() returns a document that only contains the projection fields.

Although it is similar to the find() method, the findOne() method returns a document rather than a cursor.

Example:

db.employees.findOne({gender:'male'},{gender:1, name:1})

#Output

{
"_id" : ObjectId("5f20577536c73fc3e870fda4"),
"gender" : "male",
"name" : {
"title" : "mr",
"first" : "harvey",
"last" : "chambers"
}
}

db.collection.find() Returns document or documents that satisfies the specified query criteria on the collection.

Syntax:

db.collection.find(query, projection)

Parameter

query:  The query parameter is an Optional document, which specifies a query for selection criteria using query operators.

projection: It is also an Optional document, which specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document. For details, see Projection.

Returns:

It returns the document or documents that match the criteria specified in the query. If you specify a projection parameter, find () returns a document that only contains the projection fields.

Although it is similar to the findOne() method, the find() method returns a cursor instead of documents.

Example:

db.employees.find({},{gender:1, name:1})db.employees.findOne({gender:'male'},{gender:1, name:1})

#Output


> db.employees.find({},{gender:1, name:1})
{ "_id" : ObjectId("5f20577536c73fc3e870fda4"), "gender" : "male", "name" : { "title" : "mr", "first" : "harvey", "last" : "chambers" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda5"), "gender" : "male", "name" : { "title" : "mr", "first" : "victor", "last" : "pedersen" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda6"), "gender" : "male", "name" : { "title" : "mr", "first" : "elijah", "last" : "lewis" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda7"), "gender" : "female", "name" : { "title" : "mrs", "first" : "olav", "last" : "oehme" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda8"), "gender" : "male", "name" : { "title" : "mr", "first" : "carl", "last" : "jacobs" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda9"), "gender" : "female", "name" : { "title" : "mrs", "first" : "madeleine", "last" : "till" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdaa"), "gender" : "female", "name" : { "title" : "miss", "first" : "shona", "last" : "kemperman" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdab"), "gender" : "female", "name" : { "title" : "ms", "first" : "louise", "last" : "graham" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdac"), "gender" : "male", "name" : { "title" : "mr", "first" : "zachary", "last" : "lo" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdad"), "gender" : "male", "name" : { "title" : "mr", "first" : "isolino", "last" : "viana" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdae"), "gender" : "female", "name" : { "title" : "mrs", "first" : "katie", "last" : "welch" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdaf"), "gender" : "female", "name" : { "title" : "miss", "first" : "sandra", "last" : "lorenzo" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb0"), "gender" : "female", "name" : { "title" : "miss", "first" : "mestan", "last" : "kaplangı" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb2"), "gender" : "male", "name" : { "title" : "mr", "first" : "gideon", "last" : "van drongelen" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb3"), "gender" : "female", "name" : { "title" : "miss", "first" : "maeva", "last" : "wilson" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb4"), "gender" : "female", "name" : { "title" : "ms", "first" : "anaëlle", "last" : "adam" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb5"), "gender" : "female", "name" : { "title" : "miss", "first" : "anne", "last" : "ruiz" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb6"), "gender" : "female", "name" : { "title" : "mademoiselle", "first" : "delia", "last" : "durand" } }
Type "it" for more
>

db.collection.findAndModify() Used to modifies and return a single document. By default, the returned document does not include the modifications made on the update. To return the updated document, we need to use the new option.

Syntax:

db.collection.findAndModify({
    query: <document>,
    sort: <document>,
    remove: <boolean>,
    update: <document or aggregation pipeline>,
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>,
    bypassDocumentValidation: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [ <filterdocument1>, ... ]
});

 

query:  The query parameter is an Optional document, which specifies a query for selection criteria using query operators similar to find() method. Although the query may match multiple documents, db.collection.findAndModify() will only select one document to modify.

sort: It is also an Optional document, determines which document the operation modifies if the query selects multiple documents. db.collection.findAndModify() modifies the first document in the sort order specified by this argument.

remove: An optional field of type boolean which must specify either to remove or update the field. Removes the document specified in the query field. Set this to true to remove the selected document. The default is false.

new: An optional boolean field. When true, returns the modified document rather than the original. The db.collection.findAndModify() method ignores the new option for remove operations. The default is false.

fields: An Optional document work similar to projection in find() method. The fields document specifies an inclusion of a field with 1, as in: fields: { : 1, : 1, … }.

For more details on parameter visit Mongo official doc

Returns:

To remove operations, if the query matches a document, it will return the removed document. If the query does not match a document to remove returns null.

For update operations, it will return one of the following:

If the new parameter is not set or is false:

  • The pre-modification document is returned if the query matches a document
  • Otherwise, null.

If new is set to true:

  • The modified document if the query returns a match
  • The inserted document if upsert: true and no document matches the query
  • Otherwise, null

Example:

db.userinfo.find({name:'test user'})

#Output

{ "_id" : ObjectId("5f444629c2254dfb46403a0a"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f4446c9c2254dfb46403a0b"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }


db.userinfo.findAndModify({
query: {name:'test user'},
update: { age: 22}
})

#Output

{
"_id" : ObjectId("5f444629c2254dfb46403a0a"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 21
}

Here you can see that it updated the document successfully but returned the old one with age 21.

If we again run the following query we will get the updated document with age 22.

db.userinfo.find({name:'test user'})

#Output

db.userinfo.find({name:'test user'})
{ "_id" : ObjectId("5f4448cbc2254dfb46403a0c"), "name" : "test user", "email" : "testuser@test.com", "age" : 22 }
{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

But, if we run the same update with one additional parameter new with the value true it will return the update document.

db.userinfo.findAndModify({
query: {name:'test user'},
update: {name:'test user',email:'testuser@test.com',age:23},
new :true
})

#Output

{
"_id" : ObjectId("5f4448cbc2254dfb46403a0c"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 23
}

db.collection.findOneAndDelete() Used to deletes a single document based on the filter and sort criteria, returning the deleted document. Deletes the first matching document in the collection that matches the filter. The sort parameter can be used to influence which document is deleted.

Syntax:

db.collection.findOneAndDelete(
   <filter>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     collation: <document>
   }
)

Parameter

filter: The selection criteria for the deletion same as the query in find() method. Pass and empty {} document to delete the first document returned in the collection. By default, an empty document {}.

projection: Same as the projection in find() method

sort: An Optional field. Specifies a sorting order for the documents matched by the filter.

For more details on parameter visit Mongo official doc

Returns: Returns the deleted document.

Example:

db.userinfo.find({name:'test user'})
{ "_id" : ObjectId("5f4448cbc2254dfb46403a0c"), "name" : "test user", "email" : "testuser@test.com", "age" : 23 }
{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

#Output

db.userinfo.findOneAndDelete({age:23})
{
"_id" : ObjectId("5f4448cbc2254dfb46403a0c"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 23
}

Now if run the same find command again we will only get a single record with name ‘test user’

db.userinfo.find({name:'test user'})
{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

db.collection.findOneAndReplace() Used to replace a single document based on the specified filter. The sort parameter can be used to influence which document is deleted. It works the same way findAndModify() works.

Syntax:

db.collection.findOneAndReplace( 
	<filter>, <replacement>, 
	{ projection: <document>,
	 sort: <document>, 
	 maxTimeMS: <number>,
	 upsert: <boolean>, 
	 returnNewDocument: <boolean>,
	 collation: <document> 
	} 
)

Parameter

filter: The selection criteria for the deletion same as the query in find() method. Pass and empty {} document to delete the first document returned in the collection. By default, an empty document {}.

replacement: The replacement document.

projection: Same as the projection in find() method

sort: An Optional field. Specifies a sorting order for the documents matched by the filter.

returnNewDocument: An Optional field. When true, returns the replacement document instead of the original document. Defaults to false.

For more details on parameter visit Mongo official doc

Returns: Returns either the original document or the replaced document if returnNewDocument is true.

Example:

db.userinfo.find({name:'test user'})

#Output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

db.userinfo.findOneAndReplace(
{ "age" : 21},
{name:'test user',email:'testuserAge22@test.com',age:22}
)


#Output

{
"_id" : ObjectId("5f4448cdc2254dfb46403a0d"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 21
}

db.userinfo.find({name:'test user'})

#Output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuserAge22@test.com", "age" : 22 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

But, if we pass returnNewDocument as true, it will return the replaced document.

db.userinfo.findOneAndReplace(
{ "age" : 22},
{name:'test user',email:'testuserAge23@test.com',age:23},
{returnNewDocument : true}
)

#Output
{
"_id" : ObjectId("5f4448cdc2254dfb46403a0d"),
"name" : "test user",
"email" : "testuserAge23@test.com",
"age" : 23
}

db.collection.findOneAndUpdate() Used to update a single document based on the filter and sort criteria.

Used to replace a single document based on the specified filter. The sort parameter can be used to influence which document is deleted. It works the same way findAndModify() works.

Syntax:

db.collection.findOneAndUpdate(
   <filter>,
   <update document or aggregation pipeline>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

Parameter

filter: The selection criteria for the deletion same as the query in find() method. Pass and empty {} document to delete the first document returned in the collection. By default, an empty document {}.

update: The updated document.

projection: Same as the projection in find() method

sort: An Optional field. Specifies a sorting order for the documents matched by the filter.

returnNewDocument: An Optional field. When true, returns the replacement document instead of the original document. Defaults to false.

For more details on parameter visit Mongo official doc

Returns: Returns either the original document or the replaced document if returnNewDocument is true.

Example:
db.userinfo.find({name:'test user'})

#output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuserAge23@test.com", "age" : 23 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

db.userinfo.findOneAndUpdate(
{ "age" : 23},
{ $inc: { "age" : 2 }},
{returnNewDocument : true}
)

#output

{
"_id" : ObjectId("5f4448cdc2254dfb46403a0d"),
"name" : "test user",
"email" : "testuserAge23@test.com",
"age" : 25
}

db.userinfo.find({name:'test user'})

#output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuserAge23@test.com", "age" : 25 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

Note: The update parameter only contains update operator expressions.  You can not pass an entire document to replace as we did in the findOneAndReplace() method.