簡體   English   中英

在沒有mapReduce的情況下在mongodb中合並兩個集合…?

[英]Merge two collections in mongodb without mapReduce…?

我有兩個要合並的集合。 mapReduce感覺有點矯kill過正,所以我嘗試了如下操作:

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

當然,這是無效的,因為不評估“字段”,而僅評估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 } );
            }
        }
    });
  }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM