[英]MongoDB Query in Pymongo
我有以下格式的集合:
{
"name": ....,
"users": [....,....,....,....]
}
我有兩個不同的名稱,我想找到屬於這兩個文檔的用戶總數。 現在,我正在使用Python進行此操作。 我下載了名稱為1的文檔和名稱為2的文檔,並檢查了兩個文檔中有多少用戶。 我想知道是否還有其他方法只能使用MongoDB並返回數字。
例:
{
"name": "John",
"users": ["001","003","008","010"]
}
{
"name": "Peter",
"users": ["002, "003", "004","005","006","008"]
}
由於用戶003和008屬於兩個文檔,因此結果將為2
。
我該怎么做:
doc1 = db.collection.find_one({"name":"John"})
doc2 = db.collection.find_one({"name":"Peter"})
total = 0
for user in doc1["users"]:
if user in doc2["users"]:
total += 1
您也可以使用聚合框架來執行此操作,但是我認為,只有對兩個以上的用戶執行此操作才有意義,即使您可以這樣使用它:
db.users.aggregate([
{ "$match": {
"name": { "$in": [ "John", "Peter" ] }
}},
{ "$unwind": "$users" },
{ "$group": {
"_id": "$users",
"count": { "$sum": 1 }
}},
{ "$match": { "count": { "$gt": 1 } }},
{ "$group": {
"_id": null,
"count": { "$sum": 1 }
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.