使用Pymongo获取关键用法

发布于 2025-02-06 16:40:49 字数 466 浏览 1 评论 0原文

有没有办法使用pymongo来获取键列表并计数其值?我已经使用counter对象解决了它,并通过整个集合进行循环,但是,此代码对于广泛的集合而言效率低下。有没有办法在数据库级别上解决它?

import pymongo
from collections import Counter
client = pymongo.MongoClient("XXX")
database = client["jiripesik"]
collection = database["database"]
result = collection.find({})
key_list = []
for item in result:
    for key in item.keys():
        key_list.append(key)
counter = Counter(key_list)
print(counter)

Is there a way to get a list of keys and count their values using pymongo? I have solved it using Counter object and looping through the entire collection, however, this code would be inefficient for extensive collections. Is there a way how to solve it on the database level?

import pymongo
from collections import Counter
client = pymongo.MongoClient("XXX")
database = client["jiripesik"]
collection = database["database"]
result = collection.find({})
key_list = []
for item in result:
    for key in item.keys():
        key_list.append(key)
counter = Counter(key_list)
print(counter)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明月松间行 2025-02-13 16:40:50

我怀疑这会非常表现,但是这是一种计算集合中所有顶级领域的方法。

db.collection.aggregate([
  {
    "$project": {
      "keys": {
        "$map": {
          "input": { "$objectToArray": "$ROOT" },
          "in": "$this.k"
        }
      }
    }
  },
  { "$unwind": "$keys" },
  {
    "$group": {
      "_id": "$keys",
      "count": { "$count": {} }
    }
  },
  {
    "$group": {
      "_id": null,
      "histo": {
        "$mergeObjects": {
          "$arrayToObject": [
            [ { "k": "$_id", "v": "$count" } ]
          ]
        }
      }
    }
  },
  { "$replaceWith": "$histo" }
])

尝试一下 mongoplayground.net.net

I doubt this would be very performant, but here's a way to get a count of all the top-level fields in the collection.

db.collection.aggregate([
  {
    "$project": {
      "keys": {
        "$map": {
          "input": { "$objectToArray": "$ROOT" },
          "in": "$this.k"
        }
      }
    }
  },
  { "$unwind": "$keys" },
  {
    "$group": {
      "_id": "$keys",
      "count": { "$count": {} }
    }
  },
  {
    "$group": {
      "_id": null,
      "histo": {
        "$mergeObjects": {
          "$arrayToObject": [
            [ { "k": "$_id", "v": "$count" } ]
          ]
        }
      }
    }
  },
  { "$replaceWith": "$histo" }
])

Try it on mongoplayground.net.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文