MongoDB
duplicate document
new _id
database operations
NoSQL

Duplicate a document in MongoDB using a new _id

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

To duplicate a MongoDB document with a new _id, read the original document, remove or replace its _id, and insert the copy as a new document. The key point is that _id must be unique, so you cannot insert an exact clone while keeping the original identifier.

Copy the Document in Application Code

A straightforward Node.js example looks like this:

javascript
1const { MongoClient, ObjectId } = require("mongodb");
2
3async function duplicateDocument() {
4  const client = new MongoClient("mongodb://localhost:27017");
5  await client.connect();
6
7  const collection = client.db("app").collection("items");
8  const sourceId = new ObjectId("64f000000000000000000001");
9
10  const original = await collection.findOne({ _id: sourceId });
11  if (!original) {
12    throw new Error("Document not found");
13  }
14
15  delete original._id;
16  const result = await collection.insertOne(original);
17
18  console.log("New id:", result.insertedId.toHexString());
19  await client.close();
20}
21
22duplicateDocument().catch(console.error);

Deleting _id is enough because MongoDB will generate a fresh ObjectId automatically during insertOne.

Assign Your Own New _id If Needed

If you want to control the new identifier, set it explicitly before inserting:

javascript
const copy = { ...original, _id: new ObjectId() };
await collection.insertOne(copy);

This is useful when your application needs the new ID before the insert completes or when _id uses a custom format rather than the default ObjectId.

Be Careful with Nested References

Duplicating a document does not automatically duplicate related documents in other collections. If the original contains references such as:

  • 'ownerId'
  • 'projectId'
  • 'childDocumentIds'

those values stay the same unless you change them yourself. In other words, you are cloning one document, not cloning an entire object graph.

That distinction matters in schemas where one record points to many others. A shallow duplicate may be exactly what you want, but it may also create a misleading copy that still points at the original relationships.

Shell Example

The same logic works in the Mongo shell:

javascript
const original = db.items.findOne({ _id: ObjectId("64f000000000000000000001") });
delete original._id;
db.items.insertOne(original);

That is useful for quick manual operations, but for application code you should usually prefer doing the copy in your driver code so validation and error handling remain in one place.

Consider What Should Change Besides _id

In many business cases, a true duplicate needs more than a new identifier. Timestamps, status fields, or user-facing names may also need updates:

javascript
1const copy = {
2  ...original,
3  _id: new ObjectId(),
4  status: "draft",
5  createdAt: new Date(),
6  name: `${original.name} Copy`
7};
8
9await collection.insertOne(copy);

This is often the better implementation because it makes the duplicate meaningful instead of being a byte-for-byte clone with only a different primary key.

Common Pitfalls

  • Inserting the document without changing _id. MongoDB will reject the insert because _id must be unique.
  • Forgetting that related reference fields still point to the original linked records.
  • Mutating the fetched object in place when other code still expects the original version to contain its _id.
  • Copying fields such as createdAt or status values blindly when the business meaning of the duplicate should differ.
  • Treating duplication as a database-only concern when the application actually needs validation, authorization, or audit logic around the copy.

Summary

  • To duplicate a document, fetch it, remove or replace _id, and insert the result as a new record.
  • MongoDB can generate the new _id automatically if the field is absent.
  • You can assign your own ObjectId or custom identifier when needed.
  • Review reference fields and business metadata instead of copying everything blindly.
  • A good duplicate is usually a deliberate new document, not just a raw clone.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.