且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

2个文档在MongoDB中合并

更新时间:2023-12-01 23:19:58

嘿,如果用户在两个集合中都是唯一的,请使用函数findOne(),因为find()返回一个游标.因此,要在mongoDB控制台中实现两个对象的合并,可以使用以下代码:

Hey if the user is unique in both collections use function findOne(), because find() returns a cursor. So to achieve a merge of two objects in the mongoDB console you can use the bellow code:

function mergeObjects(a,b) {
    res = new Object();

    for (attr in a) 
          res[attr] = a[attr];
    for (attr in b)
          res[attr] = b[attr];

    // only if you wanna save it in a document again
    delete res["_id"];
    return res;
 }

a = db.users.findOne({"username" : 'abc@xyz.com'})
b = db.tasks.findOne({"username" : 'abc@xyz.com'})
c = mergeObjects(a,b)

希望这可以解决您的问题.

Hopefully this solve your problems.