简体   繁体   中英

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. 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?

Please help. This may be trivial but help me.

You can use the merge() method in the BSON Api. It would give you b combined with a and store the result in b. You might want to copy b in c before doing it.

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.

For data aggregation you're better off getting acquainted with MongoDB's map/reduce features. 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.

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.

(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]}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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