如何在MongoDB中对具有多个过滤器的集合一起使用group by和lookup?

gcuhipw9  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(168)

如何在mongoDB中对同一个查询使用group by和lookup?
我有一个mongo db集合filter_weights:

` {
    "category": "laptops",
    "counter": 7,
    "filter_id": "brands"
  }

我有第二个集合filter_options_weights:

{
    "category": "laptops",
    "counter": 2,
    "filter_id": "brands", 
    "filter_option_value": "Dell"
  }, 
` {
    "category": "laptops",
    "counter": 5,
    "filter_id": "brands", 
    "filter_option_value": "Apple"
  }

我想得到的outpout是:

{
    "category": "laptops",
    "counter": 7, 
    "filter_id": "brands"
    "filter_option_value": [{"Dell": 2}, {"Apple": 5}]
  },

我试着这样做

`db.filter_weights.aggregate(
    {$match: {$and: [{category: "smartfony"}]}},
    {$group: {        _id : "$filter_id",        totalSum :{$sum: "$counter"}        }},
    {
        $lookup:
            {
                from: "filter_values_weights",
                localField:"filter_id",
                foreignField: "filter_id",
                as :"filter_id"
            }
    })`

但是我不明白如何在同一个查询中使用lookup和group by

sc4hvdpw

sc4hvdpw1#

  1. $match阶段
  2. $group-按filter_id分组。此阶段之后的输出将不再有filter_id字段,您应该参考_id。而要获得category,您可以考虑使用$first运算符。
  3. $lookup-使用_id作为localField。连接集合应该是 filter_options_weights,而不是 filter_values_weights。并以filter_option_value的形式返回联接的集合结果。
  4. $set-通过$mapfilter_option_value字段转换为新数组来设置filter_option_value字段,并使用key设置每个文档:filter_option_value和值:counter
db.filter_weights.aggregate([
  /* $match stage, */
  {
    $group: {
      _id: "$filter_id",
      category: {
        $first: "$category"
      },
      counter: {
        $sum: "$counter"
      }
    }
  },
  {
    $lookup: {
      from: "filter_options_weights",
      localField: "_id",
      foreignField: "filter_id",
      as: "filter_option_value"
    }
  },
  {
    $set: {
      filter_option_value: {
        $map: {
          input: "$filter_option_value",
          in: {
            $arrayToObject: [
              [
                {
                  k: "$$this.filter_option_value",
                  v: "$$this.counter"
                }
              ]
            ]
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

相关问题