5 Ways to Insert Documents in MongoDB

MongoDB provides many ways to insert documents into a collection.

Here are 5 ways to insert documents into a collection when using the mongo shell.

The insertOne() Method

The insertOne() method inserts a single document into a collection.

Its full name is db.collection.insertOne(), where collection is the name of the collection to insert the document into.

Here’s an example of inserting a document into a collection called pets:

db.pets.insertOne( { 
    name: "Scratch", 
    type: "Cat" 
    } )

Result:

{
	"acknowledged" : true,
	"insertedId" : ObjectId("5fe2d15637b49e0faf1af214")
}

The db.collection.insertOne() method 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 insertedId with the _id value of the inserted document.

The insertMany() Method

The insertMany() method is similar to insertOne(), except that it inserts multiple documents into a collection.

Also in a similar fashion to insertOne(), its full name is db.collection.insertMany(), where collection is the name of the collection to insert the document into. This applies to all methods listed in this article.

Here’s an example of using db.collection.insertMany() to insert multiple documents into a collection called pets:

db.pets.insertMany([
    { _id: 1, name: "Wag", type: "Dog" },
    { _id: 2, name: "Bark", type: "Dog" },
    { _id: 3, name: "Meow", type: "Cat" }
    ])

Result:

{ "acknowledged" : true, "insertedIds" : [ 1, 2, 3 ] } 

The db.collection.insertMany() method 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 values for each successfully inserted document.

The insert() Method

The insert() method is like a combination of insertOne() and insertMany(). It enables you to insert either a single document, or multiple documents into a collection.

Here’s an example of using db.collection.insert() to insert a single document:

db.pets.insert(
    { name: "Bruce", type: "Bat" }
    )

Result:

WriteResult({ "nInserted" : 1 })

When a single document is inserted, db.collection.insert() returns a WriteResult object. When an array of documents is inserted, it returns a BulkWriteResult object.

Here’s an example of using db.collection.insert() to insert multiple documents.

db.pets.insert([
    { _id: 1, name: "Wag", type: "Dog" },
    { _id: 2, name: "Bark", type: "Dog" },
    { _id: 3, name: "Meow", type: "Cat" }
    ])

Result:

BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 3,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})

As mentioned, a BulkWriteResult object is returned when inserting an array of documents.

The bulkWrite() Method

The bulkWrite() method enables you to perform bulk write operations.

Actually, insertMany() already performs bulk insert operations. Same with insert() when inserting an array of documents. But bulkWrite() enables you to perform bulk insert, update, and remove operations, all from a single method call.

Example:

db.pets.bulkWrite([
    { insertOne: { "document": { "_id": 1, "name": "Bubbles", "type": "Fish" }}},
    { insertOne: { "document": { "_id": 2, "name": "Wag", "type": "Dog" }}},
    { updateOne : {
        "filter" : { "_id" : 3 },
        "update" : { $set : { "name" : "Fluffy", "type" : "Cat" } },
        "upsert" : true
    } },
    { replaceOne : {
        "filter" : { "_id" : 4 },
        "replacement" : { "name" : "Bite", "type" : "Dog", "weight": 5 },
        "upsert" : true
    } }
])

Result:

{
	"acknowledged" : true,
	"deletedCount" : 0,
	"insertedCount" : 2,
	"matchedCount" : 0,
	"upsertedCount" : 2,
	"insertedIds" : {
		"0" : 1,
		"1" : 2
	},
	"upsertedIds" : {
		"2" : 3,
		"3" : 4
	}
}

In this case, the collection didn’t actually exist (I dropped it following the previous example), and so the only documents now inside the collection are the ones specified in this example.

Let’s take a look at the collection.

db.pets.find()

Result:

{ "_id" : 1, "name" : "Bubbles", "type" : "Fish" }
{ "_id" : 2, "name" : "Wag", "type" : "Dog" }
{ "_id" : 3, "name" : "Fluffy", "type" : "Cat" }
{ "_id" : 4, "name" : "Bite", "type" : "Dog", "weight" : 5 }

As expected, all four documents were inserted.

The Upsert Operation

This brings us to our fifth method for inserting documents into a collection in MongoDB – the upsert operation.

This is more of a conditional method for inserting documents. An upsert is an option that you can use on update operations. It only inserts a new document if the specified document doesn’t already exist. If it exists, then the original document is updated (and no document is inserted).

We’ve already seen examples of upserts. In the previous example, we specified "upsert" : true when performing the updateOne and replaceOne operations. That resulted in two documents being inserted, because the collection contained no documents that matched their filter criteria.

Here’s another example of an upsert. This time, we’ll use it on the updateOne() method.

db.pets.updateOne( 
    { name: "Harry" },
    { $set: { type: "Hamster" } },
    { upsert: true }
    )

Result:

{
	"acknowledged" : true,
	"matchedCount" : 0,
	"modifiedCount" : 0,
	"upsertedId" : ObjectId("5fe3dc44d991410169410524")
}

Here, we wanted to set all pets called Harry to be a hamster. But there were no pets called harry, so an upsert was performed.

The following methods accept the upsert parameter:

Therefore, when upsert: true is specified, these methods will perform an upsert operation when they try to update a non-existent document.