是否有 mongo 操作用于获取已排序(和/或过滤)集合中提供的文档 (_id) 之后和之前的文档计数?

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

例如,使用 pymongo:

我正在使用顺序索引添加这样的新文档。

DB_1 = mongo ["DB_1"]
collection_1 = DB_1 ["collection_1"]
collection_1.insert_one ({
    'emblem': collection_1.find ().sort ({ 
        "emblem": -1
    }).limit (1).next () ["emblem"] + 1,
    'name': 'W'
})

如您所见,名称有一个连续的“徽章” 基于它们插入的顺序(最有可能的是 如果删除文档,顺序索引就会丢失)

[{
  "emblem": 1,
  "name": "Z"
},{
  "emblem": 2,
  "name": "H"
},{
  "emblem": 3,
  "name": "T"
},{
  "emblem": 4,
  "name": "Q"
},{
  "emblem": 6,
  "name": "L"
}]

那么,经过聚合排序后,如下所列,徽章顺序为2,6,4,3,1

documents = collection_1.aggregate ([
    { 
        "$addFields": {
            "lowerName": { 
                "$toLower": "$name" 
            }
        }
    },
    { 
        #
        #   sort by name, and if names are same,
        #   then sort by emblem.
        #
        "$sort": { 
            "lowerName": 1,
            "emblem": 1
        }
    }
])

那么,进行聚合排序后, 该算法计算 之前和之后的文档计数 带有所提供标志的文件。

emblem = 6

before = 0
after = 0
counting_before = True
counting_after = False
for document in documents:
    if (document ["emblem"] == emblem):
        counting_before = False
        counting_after = True
    elif (counting_before):
        before += 1
    elif (counting_after):
        after += 1

#
# after equals 1
# before equals 3
#

是否可以计算这些计数, 作为聚合器的一部分或与另一个 mongo 一起 查询?

对于上下文,我想展示这样的东西 在浏览器中,按钮将进行搜索 相同的搜索字符串、过滤器和排序。然而 他们会有额外的投入。接下来会 还有当前页面的最后一个文档, prev 将包含当前页面中的第一个文档。

[prev (32 documents)] [next (281 documents)] 

任何帮助都会很棒,谢谢!

mongodb mongodb-query pymongo
1个回答
0
投票

您可以使用

$setWindowFields
$sum
以及 ["unbounded", -1] 和 [1, "unbounded"] 的文档窗口来统计当前文档之前/之后的文档数量。

db.collection.aggregate([
  {
    "$addFields": {
      "lowerName": {
        "$toLower": "$name"
      }
    }
  },
  {
    "$setWindowFields": {
      "partitionBy": null,
      "sortBy": {
        "lowerName": 1,
        "emblem": 1
      },
      "output": {
        "before": {
          "$sum": 1,
          "window": {
            "documents": [
              "unbounded",
              -1
            ]
          }
        },
        "after": {
          "$sum": 1,
          "window": {
            "documents": [
              1,
              "unbounded"
            ]
          }
        }
      }
    }
  }
])

蒙戈游乐场

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