【问题标题】:Count value from a Python list in MongoDB从 MongoDB 中的 Python 列表中计算值
【发布时间】:2021-12-29 06:30:21
【问题描述】:
我有一个 Python 列表 my_list,其中包含各种值:
["a", "b", "c"]
我想用 PyMongo 查询一个 MongoDB:
我可以一步一步做,循环如下:
for item in my_list:
db.collection.find({"item" : item}).count_documents()
但是,我想知道一种更好的方法,特别是避免循环。
【问题讨论】:
标签:
python
mongodb
list
pymongo
pymongo-3.x
【解决方案1】:
你可以用聚合来做到这一点
试试here
[
{
"$match": {
"item": {
"$in": [
"a",
"b",
"c"
]
}
}
},
{
"$group": {
"_id": "$item",
"count": {
"$sum": 1
}
}
}
]
$match 过滤文档,其中item 在 `["a", "b", "c"]``
然后$group 正在计算每个项目的文档。
SQL 等价物是:
SELECT item, SUM(1) FROM collection GROUP BY item