Copy Specific Document in same collection

Is there a way to copy a specific document’s structure and insert it in the same collection but add new fields to the new document using MongoSH and not Compass?

What you could try is an aggregation that $match the desired document, then use $set and $unset stages to modify the document. You add a final $merge stage to insert back the modified document.

Just run the aggregation with the $merge, once you verified that your $set and $unset do the correct modification. Make sure you $unset the _id and use whenMatched:failed otherwise you risk modifying the original document.


Thank you! I appreciate the insight, I’ll try it out.

Hello @Tre_Rush ,

As well as @steevej’s suggestion, the following may fulfill your requirements as well using mongosh in particular. It is possible to copy a specific document’s structure and insert it into the same collection but with new fields and an updated _id using MongoDB’s shell (mongo shell). The reason you need to update _id also is because no two documents can have same _id and if we try to insert the document with same _id we will get below error.

MongoServerError: E11000 duplicate key error collection: Test.performer index: id dup key: { _id: *** }

Here’s an example in JavaScript using the MongoDB shell:

// Get the document you want to copy
var docToCopy = db.collectionName.findOne({});

// Create a new document with the same structure as the original
var newDoc = Object.assign({}, docToCopy);

// Remove the _id field from the new document
delete newDoc._id;

// Add new fields to the new document
newDoc.newField1 = "value1";
newDoc.newField2 = "value2";

// Generate a new ObjectId for the _id field
newDoc._id = new ObjectId();

// Insert the new document into the collection

This will copy the structure of the document you retrieved with findOne() into a new document, add two new fields newField1 and newField2, generate a new ObjectId for the _id field, and insert the new document into the collection. If this is not what you require, could you please post more details about the use case?


1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.