Docs Menu

collection.insertMany()

On this page

  • Definition
  • Usage
  • Example
  • Parameters
  • Return Value
collection.insertMany()

Insert one or more documents into a collection and return a list of the _id values for each inserted document.

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

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))

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

insertMany(documents)
Parameter
Description

Insert Document

documents: Array<document>
An array of documents to insert into the collection.

Client Session

session: <ClientSession>
Optional. A client session that specifies the transaction context in which the operation occurs. To learn more, see Transactions.

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

Promise<result: document>
Value
Description

Inserted IDs

result.insertedIds: Array<ObjectID>
An array that contains the _id values for all documents that the insert operation added to the collection in the order that they were passed to the action.
Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.