Posted under » MongoDB on 26 Feb 2026
If you have a record that is quite similar you probably would do a 'save as' but when in mongo, it is not that easy.
MongoDB aggregation is a powerful method for processing data records in a collection, allowing for operations such as grouping, filtering, sorting, and transforming documents to return a computed result. The aggregation pipeline is the preferred and most flexible method for data processing in MongoDB, conceptually similar to an assembly line. The output of one stage serves as the input for the next, allowing complex data analysis to be broken down into manageable steps. eg.
db.hardware.aggregate([{$match: { type : 'storage', subtype: 'HDD' }}])
db.hardware.aggregate([{ $group: { "_id": "$type", "Sum of storage": { $sum: "$gb" } } } ])
When combined
db.hardware.aggregate( [
{$match: { type : 'storage', subtype: 'HDD' }},
{ $group: { _id: "$subtype", count: { $sum: 1 } } }
] );
Key pipeline stages include $match (filtering), $group (aggregation with operators like $sum or $avg), $sort (ordering), and $project (reshaping documents). Other stages like $limit, $skip, $unwind, and $out or $merge are used for pagination, flattening arrays, and exporting results
db.cakeSales.insertOne( [
{ _id: 1, flavor: "chocolate", salesTotal: 1580,
salesTrend: "up" }
] )
db.runCommand( {
aggregate: db.cakeSales.getName(),
pipeline: [ {
$merge: {
into: db.cakeSales.getName(),
let : { year: "2020" },
whenMatched: [ {
$addFields: { "salesYear": "$$year" }
} ]
}
} ],
cursor: {}
} )
db.cakeSales.find()
Output
{ "_id" : 1, "flavor" : "chocolate", "salesTotal" : 1580,
"salesTrend" : "up", "salesYear" : "2020" }
You could try run 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. Make sure you $unset the _id and use whenMatched:failed otherwise you risk modifying the original document like the above `cakeSales` code.
Another method is to use use JS var to make a copy by making sure you create a new _id because of the index.
// 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;
// Generate a new ObjectId for the _id field
newDoc._id = new ObjectId();
// Insert the new document into the collection
db.collectionName.insertOne(newDoc);