Navigation

collection.insertOne()

collection.insertOne()

Insert a single document into a collection and return the _id of the inserted document.

To call the collection.insertOne() action from a Function, get a collection handle with database.collection() then call the handle's insertOne() method.

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))

The collection.insertOne() action has the following form:

insertOne(document)
ParameterDescription

Insert Document

document: <document>
A document to insert into the collection.

The collection.insertOne() action returns a Promise that resolves to a document that describes the insert operation.

Promise<result: document>
ValueDescription

Inserted ID

result.insertedId: <ObjectID>
The _id value of the document that the insert operation added to the collection.
Give Feedback