MongoDB: How to insert a new document and get its ID (with examples)

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

Introduction

MongoDB is a powerful NoSQL database that provides high performance, high availability, and easy scalability. It works on the concept of collections and documents, rather than tables and rows, which is typical in relational databases. Each document is stored in a BSON format (Binary JSON) which allows MongoDB to include not just nested objects but also arrays and other complex data types.

In this tutorial, I’ll guide you through the process of inserting a new document into a MongoDB collection and obtaining its unique identifier, or ID. We’ll proceed from basic examples to more advanced scenarios, highlighting tips and best practices along the way.

Understanding MongoDB’s Document ID

Before we dive into inserting documents, it’s important to understand MongoDB’s document ID system. Each document stored in a MongoDB collection is automatically assigned a unique identifier known as an ObjectId. This ID serves as the primary key for the document and helps to ensure that every document can be uniquely identified within a collection.

The ObjectId is a 12-byte BSON type that guarantees uniqueness within the collection. It consists of:

  • 4 bytes representing the seconds since the Unix epoch,
  • 3 bytes of machine identifier,
  • 2 bytes of process ID, and
  • 3 bytes representing a random value.

Now, let’s start with the basics of inserting a document and retrieving its ObjectId.

Basic Document Insertion

The simplest method to insert a document is to use the insertOne method of the collection object. Here’s a basic example:

const MongoClient = require('mongodb').MongoClient;
let url = 'mongodb://localhost:27017/';
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  let dbo = db.db('mydb');
  let myobj = { name: 'John', age: 30, address: '123 Main St' };
  dbo.collection('customers').insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log('1 document inserted, ID:', res.insertedId);
    db.close();
  });
});

In this example, an object representing a customer is passed to the insertOne method. If the insertion is successful, the callback function logs the ID of the inserted document to the console.

Let’s break down the process a bit more:

  • First, we require the MongoDB client package.
  • We define our connection URL and the database we target.
  • The insertOne method takes two arguments – the document to insert, and a callback function that has an error and result parameters.
  • If there are no errors, the result object contains the insertedId field, which we access to get the assigned ObjectId of the new document.

Batch Insertion with insertMany

Sometimes, you’ll want to insert multiple documents into a MongoDB collection simultaneously. In this case, you’d use the insertMany method. Here’s how it works:

const MongoClient = require('mongodb').MongoClient;
let url = 'mongodb://localhost:27017/';
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  let dbo = db.db('mydb');
  let myobjects = [
    { name: 'John', age: 30, address: '123 Main St' },
    { name: 'Amy', age: 25, address: '456 Grand Ave' },
    // ... More objects can be added here
  ];
  dbo.collection('customers').insertMany(myobjects, function(err, res) {
    if (err) throw err;
    console.log('Number of documents inserted: ' + res.insertedCount);
    console.log('IDs of inserted documents:', res.insertedIds);
    db.close();
  });
});

This code inserts multiple customer documents into the ‘customers’ collection. When the operation completes, the callback logs the count of inserted documents and a map of the inserted IDs.

Handling Duplicate _id Fields

MongoDB won’t allow duplicate _id values in a collection, as this value must always be unique. When you attempt to insert a document without specifying an ID, MongoDB will automatically generate an ObjectId. However, if you provide your own _id value, you must ensure it doesn’t clash with any existing IDs.

If you want to handle potential duplicate ID errors gracefully, you can catch them in your error handling logic like so:

// ... Previous example code
  dbo.collection('customers').insertOne(myobj, function(err, res) {
    if (err) { 
        if(err.code === 11000) { // Error code for a duplicate key error
            console.log('Duplicate _id value encountered.');
        } else {
            throw err;
        }
    } else {
        console.log('1 document inserted, ID:', res.insertedId);
        db.close();
    }
  });
// ... Rest of the code

This simple check on the error code allows you to give more information if an insertion fails due to a duplicate ID.

Using Mongoose in Node.js Applications

In applications using Node.js, Mongoose is a popular ODM (Object Data Modeling) library for MongoDB that provides a higher-level, schema-based API to interact with MongoDB. When you insert a document using Mongoose, the process is similar to MongoDB’s native driver, with the added convenience of schema validation and middleware.

Here’s how you would create and save a new document and access its generated ID using Mongoose:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });
const customerSchema = new mongoose.Schema({
  name: String,
  age: Number,
  address: String,
});
const Customer = mongoose.model('Customer', customerSchema);
const customer = new Customer({ name: 'John', age: 30, address: '123 Main St' });

async function insertCustomer() {
  const result = await customer.save();
  console.log('Customer saved:', result);
  console.log('Customer ID:', result._id);
}

insertCustomer();

In this Mongoose example, we first define a schema and a model for customers. We then create a new customer instance and save it. Upon successful insertion, the saved document includes the _id field which we then log.

Advanced Operations

When inserting documents into MongoDB, you might need to perform additional operations, such as inserting with write concerns or bulk write operations. These operations allow for greater control over how data is inserted into the database, providing options for what occurs when an operation fails for some reason, or when insisting on a certain level of acknowledgment from the database.

MongoDB’s official documentation and API references provide detailed information on advanced insertion techniques including write concerns, bulk writes, and transactions, which are beyond the scope of this beginners’ tutorial.

Conclusion

Inserting documents in MongoDB is a fundamental operation, and obtaining the ObjectId of inserted documents is essential for many applications that rely on referencing or updating those documents later. By following the examples provided in this tutorial, you will be well equipped to perform basic inserts and handle the IDs effectively in your MongoDB-driven applications.