mongodb 比较集合中的文档

whitzsjs  于 2023-01-08  发布在  Go
关注(0)|答案(1)|浏览(176)

考虑以下名为sales的集合:

[
  {
    product: "Banana",
    timestamp: 1672992000,
    price: 5,
  },
  {
    product: "Banana",
    timestamp: 1672992001,
    price: 6,
  },
  {
    product: "Pineapple",
    timestamp: 1672992000,
    price: 9,
  },
  {
    product: "Pineapple",
    timestamp: 1672992001,
    price: 8,
  },
  {
    product: "Melon",
    timestamp: 1672992005,
    price: 15,
  },
  
]

如何查询连续价格较高的产品销售?
在我们的例子中,它是价格为6的香蕉。

  • 不是甜瓜,因为我们没有任何东西可以比较
  • 我不要菠萝,因为后一次销售的价格比前一次低

显然,每种产品可能有2次以上的销售。
有可能用聚合来做吗?

5uzkadbs

5uzkadbs1#

db.collection.aggregate([
  {
    "$setWindowFields": {
      "partitionBy": "$product",    //for each product,
      "sortBy": {timestamp: 1},     //sort by timestamp
      "output": {
        "lPrice": {
          $max: "$price",           //add a field whose value is price value of next document
          "window": {
            "documents": [1,1]
          }
        }
      }
    }
  },                               //output of this stage has current price and next price
  {
    $match: {
      $expr: {
        $gt: ["$lPrice", "$price"] //filter the documents where next price is higher than current price
      }
    }
  }
]);

Playground

相关问题