MongoDB:从集合分页数据中提取不同的值

问题描述 投票:0回答:1

我需要从集合中提取满足过滤器的“plate”的不同值。 目前的管道是:

[
   {
      "$match":{
         "$and":[
            {
               "tenant":"aq"                   
            },
            {
               "timestamp":{
                  "$gte":1697407200000
               }
            },
            {
               "timestamp":{
                  "$lte":1697580059999
               }
            }
         ]
      }
   },
   {
      "$sort":{
         "plate":1,
         "timestamp":1
      }
   },
   {
      "$group":{
         "_id":"$plate"
      }
   },
   {
      "$skip":0
   },
   {
      "$limit":40
   }
]

如果我不使用数据分页,聚合的输出是正确的,但使用分页的结果非常尴尬:第二个、第三个等等页面包含从前一个页面返回的板的重复项。

我在生产环境中使用的是 4.2.20 mongodb,目前无法更新,因此如果问题与 mongo 版本有关,我必须找到解决方法。

你能让我明白我错在哪里吗?

mongodb aggregation-framework
1个回答
0
投票

分组可以在每次调用中给出不同的顺序。所以小组赛结束后的排序很重要。

db.collection.aggregate([
  {
    "$match": {
      "$and": [
        { "tenant": "aq" },
        { "timestamp": { "$gte": 1697407200000 } },
        { "timestamp": { "$lte": 1697580059999 } }
      ]
    }
  },
  { "$group": { "_id": "$plate" } },
  { "$sort": { "_id": 1 } },
  { "$skip": 0 },
  { "$limit": 40 }
])

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.