Home > front end >  How to link unrelated collections in mongodb?
How to link unrelated collections in mongodb?

Time:10-01

I have one model called Param and it has relation with other model called Port. When I populate Param model, I get access to all Port properties. It has many properties but I will point out only those that are necessary:

//Port 
{
 username: 123556,
 rxm_name: 'Name #2'
}

There is also another, unrelated collection called Report, which has the following properties:

//Report 
{
  username: 123556,
  box_number: 4423 
}

It is worth mentioning, that there are almost 900.000 documents inside Report collection. box_number is not unique, but username is. Also, there may be some username-s from Port that exist in Report collection.

I used an aggregate function to count all different unique box_number-s. This will get amount of username-s for each box_number:

const totalUsers = await Report.aggregate([{
            "$group": {
                _id: {
                    "box_number": "$box_number",
                },
                count: {
                    $sum: 1
                }
            }
        }]);

This query returns the following:

[
 {
   _id: {
      box_number: 38032
   }, 
   count: 273
 },
 // and so on..
]

Now I must perform a query to link username,rxm_name and box_number. Basically, I must show how many username-s are in each box_number and group them by rxm_name. I am stuck for hours, but I am not able to think of such query. Are there any points that I am missing?

CodePudding user response:

You will need $lookup to link 2 collections into one single aggregate command. Here's the aggregate you can use:

db.Report.aggregate([
   {
     $lookup:
       {
         from: "Port",
         localField: "username",
         foreignField: "username",
         as: "Report2"
       }
  },
{ $unwind : "$Report2" },
{
       $group:
         {
           _id: { box_number: "$box_number", username: "$username" },
           count: {
                    $sum: 1
           },
           rxm_name: { $addToSet: "$Report2.rxm_name" }
         }
}
])
  • Related