Skip to content

Instantly share code, notes, and snippets.

@ofirski
Last active March 15, 2017 13:32
Show Gist options
  • Save ofirski/2a2344ac47eede070d28 to your computer and use it in GitHub Desktop.
Save ofirski/2a2344ac47eede070d28 to your computer and use it in GitHub Desktop.
Merge MongoDB collections
/*******************************************************************************
* Merges matching documents from source collection into desination collection
* Usage:
* mergeCollections("srcCollName", "destCollName", null, ["f1","f3"])
* mergeCollections("srcCollName", "destCollName", {xy:"z"}, ["f1","f4"])
********************************************************************************/
function mergeCollections(sourceCollection, destCollection, sourceQuery, setFields) {
var nMatched = 0;
var nModified = 0;
sourceQuery = sourceQuery || {}
db[sourceCollection].find(sourceQuery).forEach(function(sourceDoc){
var updateKeyPairs = {};
if (setFields) {
setFields.forEach(function(field){
updateKeyPairs[field] = sourceDoc[field];
});
}
else {
updateKeyPairs = sourceDoc;
}
var updateRes = db[destCollection].update(
{
_id: sourceDoc._id
},
{
$set: updateKeyPairs
}
)
nMatched += updateRes.nMatched;
nModified += updateRes.nModified;
});
print("Matched:", nMatched, "; Modified:", nModified);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment