Find in two Customers using Aggregation

Asked

Viewed 464 times

0

I need to perform a find on two Collections in mongodb using Aggregation and place the results in a single array.

I’m trying to do it this way, but it doesn’t work.

I have Visiting and Opportunities and I want to summarize the amount of records of each user. I have in both Collections the id_user variable that stores the id of the user who 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 relating to opportunity.

{_id: 1234567898765432345678, totalOpp: '2', totalVisita: "undefined"}

1 answer

1


Mongodb does not support, as far as I know, to use the Aggregate framework in more than one Center, nor does it support find, findOne and any operation other than a single Center.

Update 3.2

Mongodb in its version 3.2 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, take all documents from Collection Opportunityey where the value of the _idUser field is equal to the _idUser value of the document being processed by Aggregate and add these documents as an array named as opportunity_docs in the document being processed. If you need you can use $unwind after $lookup and then $group to get the data group you want.

For more information about Join on Mongodb 3.2 https://www.mongodb.com/blog/post/joins-and-other-aggregation-enhancements-coming-in-mongodb-3-2-part-1-of-3-introduction

For more information about the new $lookup operator https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.