mongodb组和计数数组属性的元素

0lvr5msh  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(205)

我有两个系列
客户:

[
          {
            "_id": 1,
            "NAME": "CUSTOMER A"
          },
          {
            "_id": 1,
            "NAME": "CUSTOMER B"
          }
        ]

门票:

[
          {
            "_id": 1,
            "CUSTOMER": 2,
            "NUMBERS": [1,2,3]
          },{
            "_id": 2,
            "CUSTOMER": 2,
            "NUMBERS": [4]
          },{
            "_id": 3,
            "CUSTOMER": 1,
            "NUMBERS": [25]
          }
        ]

我需要用这种方法从高到低数出每位顾客订购的机票上有多少个号码
结果:

[
          {
            "_id": 2,
            "NAME": "CUSTOMER B",
            "COUNTNUMBERS": 4
          },
          {
            "_id": 1,
            "NAME": "CUSTOMER A",
            "COUNTNUMBERS": 1
          }
        ]

最接近我需要的示例是这个,但它仍然不是我需要的

db.tickets.aggregate([{
        $unwind: "$CUSTOMER"
    },
    {
        $group: {
            _id: "$CUSTOMER",
            NUMBERS: { $sum: 1 }
        }
    }, 
    {
        $lookup: {
            let: { "customerId": "$_id"},
            from: "customers",
            pipeline: [
                { $match: { $expr: { $eq: ["$_id", "$$customerId"] } } }
            ],
            as: "CUSTOMER"
        }
    }
])
8wtpewkr

8wtpewkr1#

db.tickets.aggregate([
  // Join the customers collection to get the customer names
  {
    $lookup: {
      from: "customers",
      localField: "CUSTOMER",
      foreignField: "_id",
      as: "customer_info"
    }
  },
  // Flatten the array from the lookup
  { $unwind: "$customer_info" },
  // Group by customer ID and count the numbers in the NUMBERS array
  {
    $group: {
      _id: "$CUSTOMER",
      NAME: { $first: "$customer_info.NAME" },
      COUNTNUMBERS: { $sum: { $size: "$NUMBERS" } }
    }
  },
  // Sort by COUNTNUMBERS in descending order
  { $sort: { COUNTNUMBERS: -1 } }
])

相关问题