MongoDB: Insert multiple documents and get their IDs (with examples)

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

Learn to efficiently insert multiple documents into a MongoDB collection and retrieve their unique identifiers (_id) with a series of practical examples. Whether you’re developing a web application, working on a large-scale data processing task, or simply looking to expand your MongoDB skill set, this tutorial will guide you through the process from basic to advanced scenarios, ensuring a solid understanding of how MongoDB handles document insertion and ID generation.

Prerequisites

Before diving into the examples, ensure you have:

  • MongoDB installed and running locally or accessible remotely.
  • A basic understanding of MongoDB collections and documents.
  • A programming language environment ready (we’ll use JavaScript with Node.js in our examples).
  • The MongoDB Node.js driver installed if you’re following along with the code examples.

Understanding MongoDB IDs

Each document in MongoDB comes with a unique identifier, the _id field. By default, MongoDB generates a BSON ObjectId for this field, though you can specify custom IDs. Knowing how to retrieve these IDs following insertion operations is crucial for many applications, including relationship mapping, logging, and data referencing.

Basic Insert Operation

Let’s start with a basic example where we insert multiple documents into a collection and retrieve their IDs. For this, we use the insertMany function.

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';

let client = new MongoClient(url, { useUnifiedTopology: true });

async function run() {
  try {
    await client.connect();
    console.log('Connected correctly to server');
    const db = client.db(dbName);
    const col = db.collection('documents');

    // Insert Multiple Documents
    let r = await col.insertMany([{name: 'Document 1'}, {name: 'Document 2'}]);
    console.log('Inserted documents:', r.insertedCount);
    console.log('IDs of inserted documents:', r.insertedIds);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

This simple script connects to a MongoDB database, inserts two documents into a specified collection, and logs the number of documents inserted along with their generated IDs. The insertedIds property of the result object provides an array of the inserted document IDs.

Handling Custom IDs

It’s also possible to specify custom IDs for each document to have more control over your data schema. Here’s how you can do that:

let r = await col.insertMany([
  { _id: 'customId1', name: 'Custom Document 1' },
  { _id: 'customId2', name: 'Custom Document 2' }
]);
console.log('Custom IDs:', r.insertedIds);

This modifies our previous example to explicitly set _id fields. As a result, the insertedIds property will reflect the custom IDs you’ve provided.

Batch Insertion with Error Handling

When inserting multiple documents, it’s also crucial to implement error handling to manage cases where some documents might not be inserted due to duplicates or other issues. Here’s how you can handle errors during batch insertions:

client.connect()
.then(() => {
  const db = client.db(dbName);
  const col = db.collection('documents');
  return col.insertMany([
    { _id: 1, name: 'Document 1' },
    { _id: 2, name: 'Document 2' },
    { _id: 1, name: 'Duplicate Document' }
  ], { ordered: false })
  .then(r => console.log('Inserted documents:', r.insertedCount))
  .catch(err => console.error('Insertion error:', err.message));
})
.finally(() => client.close());

In this example, we attempt to insert three documents, with one being a deliberate duplicate to trigger an error. The ordered: false option allows the insertion of non-duplicate documents to proceed even if one fails, and we catch any errors to manage them gracefully.

Conclusion

Understanding how to insert multiple documents into MongoDB and retrieve their IDs is a foundational skill for any developer working with MongoDB. This tutorial has demonstrated through examples how to perform basic insertions, handle custom IDs, and manage batch insertions with error handling. By mastering these techniques, you’ll be better equipped to develop robust, data-driven applications with MongoDB.