Reputation: 591
I have a collection A that has documents in form of:
{
_id: 12345,
title: "title"
}
and document B in form of:
{
_id: 12345,
newAttribute: "newAttribute12345"
}
I want to update collection A to have documents like:
{
_id: 12345,
title: "title"
newAttribute: "newAttribute12345"
}
At this time I do it with
update({_id: doc._id}, {$set: {newAttribute: doc.newAttrubute}})
, but I need to run it 10,000 in a loop for all my documents. How can I update multiple documents like these (by _id) in 1 db call or in most efficient way? (this is basically a join/bulk update attributes operation)
I use mongodb 2.6
Upvotes: 0
Views: 824
Reputation: 7840
consider following scenario, two collections name as title
and attribute
.
title
collection contains following documents :
[{
_id: 12345,
title: "title"
},
{
_id: 12346,
title: "title1"
}]
and attribute
collection contains following document :
[{
_id: 12345,
newAttribute: "newAttribute12345"
},
{
_id: 12346,
newAttribute: "newAttribute12346"
},
{
_id: 12347,
newAttribute: "newAttribute12347"
}]
And you want to update title
collection as using this criteria title._id = attribute._id
use mongo bulk update with following script :
var bulk = db.title.initializeOrderedBulkOp();
var counter = 0;
db.attribute.find().forEach(function(data) {
var updoc = {
"$set": {}
};
var updateKey = "newAttribute";
updoc["$set"][updateKey] = data.newAttribute;
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
// Drain and re-initialize every 1000 update statements
if(counter % 1000 == 0) {
bulk.execute();
bulk = db.title.initializeOrderedBulkOp();
}
})
// Add the rest in the queue
if(counter % 1000 != 0) bulk.execute();
Upvotes: 2
Reputation: 61235
You can use the cursor.forEach
method
db.collectionA.find().forEach(function(docA){
db.collectionB.find().forEach(function(docB){
if(docA._id === docB._id){
docA.newAttribute = docB.newAttribute;
db.collectionA.save(docA);
}
})
})
> db.collectionA.find()
{ "_id" : 12345, "title" : "title", "newAttribute" : "newAttribute12345" }
Upvotes: 0
Reputation: 591
A possible/problematic answer is hacky join in mongo (maybe there is something better): http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/
The problem with this is that I have to swap the collections later and this requires me to know the properties of my collection
var r = function(key, values){
var result = { prop1: null, prop2: null };
values.forEach(function(value){
if (result.prop1 === null && value.prop1 !== null) {
result.prop1 = value.prop1;
}
if (result.prop2 === null && value.prop2 !== null) {
result.prop2 = value.prop2;
}
})
return result;
};
var m = function(){
emit(this._id, { prop1: this.prop1, prop2: this.prop2 })
}
db.A.mapReduce(m1, r, { out: { reduce: 'C' }});
db.B.mapReduce(m1, r, { out: { reduce: 'C' }});
Upvotes: 0