簡體   English   中英

我怎樣才能在這種查詢中從我的收藏中獲得最小值和最大值 mongodb

[英]how can i get min and max value from my collection in this kind of query mongodb

我正在嘗試從我的文檔集合中獲取名為 productPrice 的屬性的最小值和最大值,我該怎么做......?

另外,我不能使用多個查找,因為它顯示 cursor 錯誤

        let query = collection
            .find(JSON.parse(queryStr))
            .sort(
                req.query.sort === "discount"
                    ? { discountPercent: -1 }
                    : req.query.sort === "high"
                    ? { productPrice: -1 }
                    : req.query.sort === "low"
                    ? { productPrice: 1 }
                    : req.query.sort === "rating"
                    ? { productRating: -1 }
                    : null,
            )
            .collation({ locale: "en_US", numericOrdering: true })
            .limit(limit)
            .skip(startIndex)
            .toArray();

在不知道您的模式、數據示例或預期 output 並回答您的問題“如何獲得最大值和最小值”的情況下:

我想到的第一件事是......做兩個查詢:

var min = await db.collection.find(yourFilter).sort({ "productPrice": -1 }).limit(1)
var max = await db.collection.find(yourFilter).sort({ "productPrice": 1 }).limit(1)

但是,在不知道您的模式的情況下,也許這可以幫助您:

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "max": {
        "$max": "$productPrice"
      },
      "min": {
        "$min": "$productPrice"
      }
    }
  }
])

這只是$group階段,如果您使用$match添加過濾器並按特定字段分組,您可以獲得所需的數據。

結果是這樣的:

{
   "_id": null,
   "max": 8,
   "min": 1
}

您在哪里獲得最大值和最小值。

這里的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM