MongoDB copy a field to another collection with a foreign key -
i want copy on color user collection car collection. i'm using foreign key userid.
> db.test1.user.find() { "_id" : objectid("515f7db83f71d6bcb1c41a48"), "age" : 33, "color" : "blue" } { "_id" : objectid("515f7dc03f71d6bcb1c41a49"), "age" : 52, "color" : "red" } { "_id" : objectid("515f7dc43f71d6bcb1c41a4a"), "age" : 43, "color" : "yellow" } > db.test2.car.find() { "_id" : objectid("515f84883f71d6bcb1c41a54"), "speed" : 291, "userid" : objectid("515f7db83f71d6bcb1c41a48") } { "_id" : objectid("515f84883f71d6bcb1c41a55"), "speed" : 202, "userid" : objectid("515f7db83f71d6bcb1c41a49") } { "_id" : objectid("515f84883f71d6bcb1c41a56"), "speed" : 193, "userid" : objectid("515f7db83f71d6bcb1c41a4a") } here query
db.test1.user.find().foreach( function(x) { db.test2.car.update( { userid: x._id }, { $set: { color: x.color} } ) } ); i want result:
> db.test2.car.find() { "_id" : objectid("515f84883f71d6bcb1c41a54"), "speed" : 291, "userid" : objectid("515f7db83f71d6bcb1c41a48"), "color" : "blue" } { "_id" : objectid("515f84883f71d6bcb1c41a55"), "speed" : 202, "userid" : objectid("515f7db83f71d6bcb1c41a49"), "color" : "red" } { "_id" : objectid("515f84883f71d6bcb1c41a56"), "speed" : 193, "userid" : objectid("515f7db83f71d6bcb1c41a4a"), "color" : "yellow" } thanks !
there several issues test set up:
- case of field names not match (you referencing
colorinstead ofcolorwhen copying) - only 1 of example foreign keys matches in target collection:
objectid('515f7db83f71d6bcb1c41a48') - your update affect first matching document "foreign key". fine 1:1 relationship, not 1:many
a corrected example taking above account (aside non-matching keys):
db.test1.user.find().foreach( function(x) { db.test2.car.update( // query { userid: x._id }, // update { $set: { color: x.color} }, // options: { "multi" : true } // update matching documents ); } ); which results in setting {color:blue} foreign key matches in sample documents:
db.test2.car.find() { "_id" : objectid("515f84883f71d6bcb1c41a55"), "speed" : 202, "userid" : objectid("515f7db83f71d6bcb1c41a49") } { "_id" : objectid("515f84883f71d6bcb1c41a56"), "speed" : 193, "userid" : objectid("515f7db83f71d6bcb1c41a4a") } { "_id" : objectid("515f84883f71d6bcb1c41a54"), "color" : "blue", "speed" : 291, "userid" : objectid("515f7db83f71d6bcb1c41a48") }
Comments
Post a Comment