In MongoDB the db.collection.insertOne()
method inserts a single document into a collection.
The collection
part is the name of the collection to insert the document into.
Example
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
astrue
if the operation ran with write concern orfalse
if write concern was disabled. - A field
insertedId
with the_id
value of the inserted document.
Now if we use db.collection.find()
to look at the collection, we will see the newly added document.
db.pets.find().pretty()
Result:
{ "_id" : ObjectId("5fe2d15637b49e0faf1af214"), "name" : "Scratch", "type" : "Cat" }
I also used pretty()
to format the document so that it’s easier to read.
In this case, our document is the only one in the collection, and so only one document was returned.
However, if the collection was large, we could use the ID (provided in the return document when we did the insert) to narrow the result to just this document.
db.pets.find({_id: ObjectId("5fe2d15637b49e0faf1af214")} ).pretty()
Result:
{ "_id" : ObjectId("5fe2d15637b49e0faf1af214"), "name" : "Scratch", "type" : "Cat" }
What if the Collection Doesn’t Exist?
If the collection doesn’t exist, it is created, and the document is added to it.
If the collection already exists, then the document is simply added to it.
When I created this example, the collection didn’t exist, and so the insert operation created it.
The _id
Field
The _id
field is a unique identifier field in MongoDB.
You can provide your own _id
field in the document. If you do, then its value must be unique within the collection. This is because your _id
field will be used as the unique identifier of the document.
Here’s an example of inserting a document with its own _id
field.
db.pets.insertOne( {
_id: 1,
name: "Fetch",
type: "Dog"
} )
Result:
{ "acknowledged" : true, "insertedId" : 1 }
Now let’s look at the collection again.
db.pets.find()
Result:
{ "_id" : ObjectId("5fe2d15637b49e0faf1af214"), "name" : "Scratch", "type" : "Cat" } { "_id" : 1, "name" : "Fetch", "type" : "Dog" }
More Information
The db.collection.insertOne()
method also accepts a writeConcern
argument, which describes the level of acknowledgment requested from MongoDB for write operations.
See the MongoDB documentation for db.collection.insertOne()
for more information.