Last active
March 15, 2017 13:32
-
-
Save ofirski/2a2344ac47eede070d28 to your computer and use it in GitHub Desktop.
Merge MongoDB collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************************************************* | |
* 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