我是 MongoDB 和 Python 腳本的新手。我很困惑如何$match
在管道中處理一個術語。
假設我管理一個圖書館,其中書籍在 MongoDB 中作為 JSON 檔案進行跟蹤。每本書的副本都有一個 JSON。book.JSON 檔案如下所示:
{
"Title": "A Tale of Two Cities",
"subData":
{
"status": "Checked In"
...more data here...
}
}
在這里,status
將是一組有限字串中的一個字串,可能只是:{“Checked In”、“Checked Out”、“Missing”等。} 但還要注意,可能根本沒有status
欄位:
{
"Title": "Great Expectations",
"subData":
{
...more data here...
}
}
好的:我正在嘗試在執行以下操作的 Python 腳本中撰寫 MongoDB 管道:
- 對于圖書館中的每本書:
status
對欄位的不同實體進行分組和計數
所以我的 Python 腳本的目標輸出將是這樣的:
{ "A Tale of Two Cities" 'Checked In' 3 }
{ "A Tale of Two Cities" 'Checked Out' 4 }
{ "Great Expectations" 'Checked In' 5 }
{ "Great Expectations" '' 7 }
這是我的代碼:
mydatabase = client.JSON_DB
mycollection = mydatabase.JSON_all_2
listOfBooks = mycollection.distinct("bookname")
for book in listOfBooks:
match_variable = {
"$match": { 'Title': book }
}
group_variable = {
"$group":{
'_id': '$subdata.status',
'categories' : { '$addToSet' : '$subdata.status' },
'count': { '$sum': 1 }
}
}
project_variable = {
"$project": {
'_id': 0,
'categories' : 1,
'count' : 1
}
}
pipeline = [
match_variable,
group_variable,
project_variable
]
results = mycollection.aggregate(pipeline)
for result in results:
print(str(result['Title']) " " str(result['categories']) " " str(result['count']))
正如您可能會說的那樣,我對自己在做什么幾乎一無所知。當我運行代碼時,我得到一個錯誤,因為我試圖參考我的$match
術語:
Traceback (most recent call last):
File "testScript.py", line 34, in main
print(str(result['Title']) " " str(result['categories']) " " str(result['count']))
KeyError: 'Title'
那么一個$match
術語不包含在管道中嗎?還是我沒有將它包含在group_variable
or中project_variable
?
總的來說,上面似乎有很多代碼可以做一些相對容易的事情。有沒有人看到更好的方法?很容易在網上找到簡單的例子,但這比我能找到的任何東西都要復雜一步。謝謝你。
uj5u.com熱心網友回復:
這是和的所有書籍的一個聚合管道。"$group"
"Title"
"subData.status"
db.collection.aggregate([
{
"$group": {
"_id": {
"Title": "$Title",
"status": {"$ifNull": ["$subData.status", ""]}
},
"count": { "$count": {} }
}
},
{ // not really necessary, but puts output in predictable order
"$sort": {
"_id.Title": 1,
"_id.status": 1
}
},
{
"$replaceWith": {
"$mergeObjects": [
"$_id",
{"count": "$count"}
]
}
}
])
“書籍”之一的示例輸出:
{
"Title": "mumblecore",
"count": 3,
"status": ""
},
{
"Title": "mumblecore",
"count": 3,
"status": "Checked In"
},
{
"Title": "mumblecore",
"count": 8,
"status": "Checked Out"
},
{
"Title": "mumblecore",
"count": 6,
"status": "Missing"
}
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494683.html
下一篇:“non_field_errors”:[“無效資料。期望字典,但得到了QuerySet。”]來自djongo的序列化程式或模型的問題