简体   繁体   中英

MongoDB aggregate & lookup between 3 collections

I am trying to create a simple DB of customers/products/orders. This is the customer collection

This is the order collection

This is the product collection

I prefered using ref key and not embedded document just to exercise. What I am trying to so is to group by customer name and then sum for each customer his total orders= Sum (Product_price x Quantity).

This is the query I tried but it doesn't work:/

db.customers.aggregate([
  {$lookup:{from:"orders", localField:"ordered",foreignField:"_id", as:"Bought"}},
  {$lookup:{from:"products", localField:"Bought.Includes.product",foreignField:"_id", as:"User_products"}},
  {$group:{_id:{name:"$name"},total: { $multiply: [ "$price", "$quantity" ] }}},
  {$project: {name:1, total:1}  }
]).pretty()

You almost got it, just a few issues. Explanation in the code's comment

[
  {
    $lookup: {
      from: "orders",
      localField: "ordered",
      foreignField: "_id",
      as: "Bought"
    }
  },
  {
    $unwind: '$Bought' //  You have to use $unwind on an array if you want to use a field in the subdocument array to further usage with `$lookup` 
  },
  {
    $unwind: '$Bought.Includes' // Also $unwind here
  },
  {
    $lookup: {
      from: "products",
      localField: "Bought.Includes.product",
      foreignField: "_id",
      as: "User_products"
    }
  },
  {
    $unwind: '$User_products' // also $unwind here
  },
  {
    $group: {
      _id: "$name" , // [optional] only one field to use as key, no need to wrap in an object
      total: {
        $sum: { // don't forget to $sum here
          $multiply: [
            "$User_products.Price", // access the value with the full object path
            "$Bought.Includes.quantity" // access the value with the full object
          ]
        } 
      }
    }
  },
]

More about $unwind

Tip: make sure you have consistent usage with uppercase/lowercase, I noticed you use product vs Price vs Quantity it will be more prone to misspellings

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