Find in two collections using aggregation

0

I need to perform a find on two collections in mongodb using aggregation and put the results into a single array.

I'm trying to do this, but it does not work.

I have the collection Visits and Opportunities and want to summarize the amount of records of each user. I have in both collections the variable id_user that stores the id of the user that registered it.

 Visita.aggregate([  
                          {  
                            "$match": {$and: [{Active: true}, {Root: true}]}
                          },
                          {
                            "$group": { _id: "$_idUser", totalVisita: {   $sum:1} }   
                          },  
                          OpportunityEY.aggregate([  
                            {  
                              "$group": { _id: "$_idUser", totalOpp: {   $sum:1} }   
                            },  
                          ])  
                        ]).exec(function(err, result){  
                          var managers = new Array();  
                          for (var i = 0; i < result.length; i++) {  
                            var manager = new Manager();  
                            manager._id = (result[i]._id);  
                            manager.totalVisit =   result[i].totalVisita;  
                            manager.totalOpp = result[i].totalOpp;  
                            managers.push(manager);  

However, it only takes information about the opportunity.

{_id: 1234567898765432345678, totalOpp: '2', totalVisita: "undefined"}
    
asked by anonymous 16.03.2016 / 15:31

1 answer

1

MongoDB does not support, so far as I know, to use the aggregate framework in more than one collection, nor does it support find, findOne, and any type of operation other than a single collection.

Update 3.2

MongoDB 3.2 has added support for LeftOutJoin using the new $ lookup operator in the aggregate framework.

You could do it this way.

$lookup: {
    from: 'OpportunityEY',
    localField: '_idUser',
    foreignKey: '_idUser,
    as: 'opportunity_docs'
}

What this operator is going to do is grab all documents in the OpportunityEY collection where the value of the _idUser field is equal to the _idUser value of the document being processed by the aggregate and add these documents as an array named opportunity_docs in the document that is being processed. If you need to use $ unwind after $ lookup and then $ group to get the data group you want.

For more information on Join in MongoDB 3.2 link

For more information about the new $ lookup operator link

    
30.03.2016 / 16:06