简体   繁体   English

2个文档在MongoDB中合并

[英]2 documents merge in MongoDB

I need to get data from two documents from different collections(1 common field in them, no change to the db) in MongoDB. 我需要从MongoDB中的不同集合(其中有1个公共字段,对数据库没有更改)的两个文档中获取数据。 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')

How to I get a variable c which has a and b merged? 我如何获得具有a和b合并的变量c?

Please help. 请帮忙。 This may be trivial but help me. 这可能是微不足道的,但对我有帮助。

You can use the merge() method in the BSON Api. 您可以在BSON Api中使用merge()方法 It would give you b combined with a and store the result in b. 它将给您b与a组合,并将结果存储在b中。 You might want to copy b in c before doing it. 您可能需要先在c中复制b。

Hey if the user is unique in both collections use function findOne(), because find() returns a cursor. 嘿,如果用户在两个集合中都是唯一的,请使用函数findOne(),因为find()返回一个游标。 So to achieve a merge of two objects in the mongoDB console you can use the bellow code: 因此,要在mongoDB控制台中实现两个对象的合并,可以使用以下代码:

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. 希望这可以解决您的问题。

For data aggregation you're better off getting acquainted with MongoDB's map/reduce features. 对于数据聚合,最好先熟悉MongoDB的地图/缩小功能。 You can read more about it here . 您可以在此处了解更多信息。

Once you figure it out it won't be difficult to write the Map (retrieve data) and Reduce (aggregate data) functions. 一旦弄清楚了,编写Map(检索数据)和Reduce(聚合数据)功能就不会很困难。

You will have to do this in your application. 您将必须在您的应用程序中执行此操作。 Don't worry about having to run two queries, as it's not necessarily going to be slower than running one complex one. 不必担心必须运行两个查询,因为它不一定比运行一个复杂的查询要慢。

I know it will probably be not your case, but if you are using clojure, an elegant solution is to use the merge-with function after retrieving the documents from mongo. 我知道这可能不是您的情况,但是如果您正在使用clojure,一种不错的解决方案是在从mongo中检索文档后使用merge-with函数。

(def a {
        :scA {:a [1, 2]}
        :scB {:b [3, 4]}
})
; {:scA {:a [1 2]}, :scB {:b [3 4]}}

(def b {
        :scA {:c [5, 6]}
        :scC {:d [7, 8]}
})
; {:scA {:c [5 6]}, :scC {:d [7 8]}}

(merge-with into a b)
; {:scA {:a [1 2], :c [5 6]}, :scB {:b [3 4]}, :scC {:d [7 8]}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM