Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two fields from different documents in Mongodb

Tags:

mongodb

I have these documents in a collection :

   {topic : "a",
    messages : [ObjectId("21312321321323"),ObjectId("34535345353"),...]
   },
   {topic : "b,
    messages : [ObjectId("1233232323232"),ObjectId("6556565656565"),...]
   }

Is there a posibility to get a result with the combination of messages fields ? I like to get this for example :

     {[
       ObjectId(""),ObjectId(""),ObjectId(""),ObjectId("")
     ]}

I thought that this was possible with MapReduce but in my case the documents doesn't have anything in common. Right now I'm doing this in the backend using javascript and loops, but i think that this isn't the best option. Thanks.

like image 445
Daniel Flores Avatar asked Jan 12 '13 23:01

Daniel Flores


1 Answers

You could use the $group operator in the Aggregation Framework. To use the Aggregation Framework you will want to be sure you're running on MongoDB 2.2 or newer, of course.

If used with $push you will get all the lists of messages concatenated together.

db.myCollection.aggregate({ $group: { messages: { $push: '$messages' } } });

If used with $addToSet you will get only the distinct values.

db.myCollection.aggregate({ $group: { messages: { $addToSet: '$messages' } } });

And if you want to filter down the candidate documents first, you can use $match.

db.myCollection.aggregate([
    { $match: { topic: { $in: [ 'a', 'b' ] } } },
    { $group: { matches: { $sum: 1 }, messages: { $push: '$messages' } } }
]);
like image 64
jared Avatar answered Oct 20 '22 22:10

jared