I have two collections that I want to merge. mapReduce felt a bit overkill so I tried something like this:
// setup
use testdb
db.users.remove();
db.profiles.remove();
db.users.save({email: "foo@bar.com", a: "a"});
db.profiles.save({email: "foo@bar.com", b: "b"});
// merge it
db.users.find().forEach(
function(user) {
print("updating user " + user.email);
db.profiles.find({email: user.email}).forEach(function(profile) {
for(field in profile) {
if(profile.hasOwnProperty(field) && !(field in user)) {
db.users.update( {_id: user._id}, { $set : { field : profile[field] } } );
}
}
});
}
);
db.users.find().pretty();
Of course this is broken since "field" is not evaluated but just the json field name. I wanted to do update rather than save though. I suck at js so my question is just: how do I evaluate the field name so I can use it in the json object that $set needs?
Ah, ok. The [] syntax works of course:
db.users.find().forEach(
function(user) {
print("updating user " + user.email);
db.profiles.find({email: user.email}).forEach(function(profile) {
for(field in profile) {
if(profile.hasOwnProperty(field) && !(field in user)) {
var setObj = {};
setObj[field] = profile[field];
db.users.update( {_id: user._id}, { $set : setObj } );
}
}
});
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.