mongodb 查询对象数组中的最低价格

mongodb query to find the min price in array of objects

我的文档:

[{
"title": "lenovo x-100",
"brand": "lenovo",
"category": "laptops",
"variant": [{
    "price": 30000,
    "RAM": "4GB",
    "storage": "256GB",
    "screen": "full hd",
    "chip": "i3"
}, {
    "price": 35000,
    "RAM": "8GB",
    "storage": "512GB",
    "screen": "full hd",
    "chip": "i5"
}, {
    "price": 40000,
    "RAM": "12GB",
    "storage": "2TB",
    "screen": "uhd",
    "chip": "i7"
}],
"salesCount": 32,
"buysCount": 35,
"viewsCount": 60
},
{
"title": "samsung12",
"brand": "lenovo",
"category": "mobile phones",
"variant": [{
    "price": 11000,
    "RAM": "4GB",
    "ROM": "32GB"
}, {
    "price": 16000,
    "RAM": "6GB",
    "ROM": "64GB"
}, {
    "price": 21000,
    "RAM": "8GB",
    "ROM": "128GB"
}],
"salesCount": 48,
"buysCount": 39,
"viewsCount": 74
}

预期输出

{
 _id:"lenovo",
 minPrice:1100
}

我试过这种聚合方式

[{
$match: {
    brand: 'lenovo'
}
}, {
 $group: {
    _id: '$brand',
    prices: {
        $min: '$variant.price'
    }
}
}, {
$unwind: {
    path: '$prices'
}
}, {
$group: {
    _id: '$_id',
    minPrice: {
        $min: '$prices'
    }
}
}]

我想找到基于品牌的最低价格,此查询返回预期输出但有没有更好的方法来获得预期结果,因为在某种意义上使用 $unwind 运算符相当昂贵,它可能需要更长的时间执行时间,希望提前正数response.Thanks

您可以使用$reduce替换第二个$group阶段。

  1. $match

  2. $group - 将 variant.price 推入新数组并生成数组的嵌套数组。

  3. $project:

    3.1。 $reduce - 用于通过 $concat 将结果 2 的嵌套数组展平为一个数组。

    3.2。 $min - Select 结果的最小值 3.1.

db.collection.aggregate([
  {
    $match: {
      brand: "lenovo"
    }
  },
  {
    $group: {
      _id: "$brand",
      prices: {
        $push: "$variant.price"
      }
    }
  },
  {
    $project: {
      _id: 1,
      minPrice: {
        $min: {
          "$reduce": {
            "input": "$prices",
            "initialValue": [],
            "in": {
              "$concatArrays": [
                "$$value",
                "$$this"
              ]
            }
          }
        }
      }
    }
  }
])

Sample Mongo Playground