Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在没有mapReduce的情况下合并mongodb中的两个集合…;?_Javascript_Json_Mongodb - Fatal编程技术网

Javascript 在没有mapReduce的情况下合并mongodb中的两个集合…;?

Javascript 在没有mapReduce的情况下合并mongodb中的两个集合…;?,javascript,json,mongodb,Javascript,Json,Mongodb,我有两个要合并的集合。mapReduce感觉有点过头了,所以我尝试了以下方法: // 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(use

我有两个要合并的集合。mapReduce感觉有点过头了,所以我尝试了以下方法:

// 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();

当然,这是不正确的,因为“field”不是计算的,而是json字段名。我想更新而不是保存。我讨厌js,所以我的问题是:如何计算字段名,以便在$set需要的json对象中使用它?

啊,好的。[]语法当然有效:

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 } );
            }
        }
    });
  }
);