2个文档在MongoDB中合并 [英] 2 documents merge in MongoDB

查看:488
本文介绍了2个文档在MongoDB中合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从MongoDB中的不同集合(其中有1个公共字段,对数据库没有更改)的两个文档中获取数据.我是新手,请帮助我

I need to get data from two documents from different collections(1 common field in them, no change to the db) in MongoDB. I am a newbie and please help me with this

a = db.users.find(username:'abc@xyz.com')
b = db.tasks.find(username:'abc@xyz.com')

我如何获得合并了a和b的变量c?

How to I get a variable c which has a and b merged?

请帮助.这可能微不足道,但对我有帮助.

Please help. This may be trivial but help me.

推荐答案

嘿,如果用户在两个集合中都是唯一的,请使用函数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.

这篇关于2个文档在MongoDB中合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆