我正在使用 MongoDb 學習 Django,并且有一個要搜索的集合。這是集合中的示例檔案:
{
"_id": { "$oid": "62615907568ddfca4fef3a25" },
"word": 'entropy,
"count": 4,
"occurrence": [
{"book": "62615907568ddfca4fef3a23", "year": 1942, "sentence": 0 },
{"book": "62615907568ddfca4fef3a23", "year": 1942, "sentence": 5 },
{"book": "62615907568ddfca4fef3a75", "year": 1928, "sentence": 0 },
{"book": "62615907568ddfca4fef3a90", "year": 1959, "sentence": 8 }
]
}
我想檢索特定檔案(單詞)的“出現”欄位的陣列元素:
- 按年份排序
- 一年范圍內
- 有偏移限制
- 計算總結果(無限制/偏移)
到目前為止我所做的是:
offset= 0
limit= 10
search= {'$and': [{"_id": word_id_obj, "occurrence": {"$elemMatch": {"year": {"$gte": 1940, "$lte": 1960}}}}]}
word_docs= wordcollec.aggregate([
{"$match": search},
{"$project":
{"occurrence":
{"$slice": ['$occurrence', offset, limit]}
}
},
{"$sort": {'occurrence.year': -1}}
])
# Count total results
recnt= wordcollec.aggregate([{"$match": search}, {'$group' : {"_id": "$_id", "sno" : {"$sum" : {"$size": "$occurrence"}}}}])
年份范圍,計數不起作用,我無法對它們進行排序。我怎樣才能為此重寫我的查詢?
提前致謝。
uj5u.com熱心網友回復:
$unwind然后使用$sort
db.collection.aggregate([
{
$match: {
_id: { "$oid": "62615907568ddfca4fef3a25" },
occurrence: { $elemMatch: { year: { $gte: 1940, $lte: 1960 } } }
}
},
{
$set: { totalWithoutLimitOrOffset: { $size: "$occurrence" } }
},
{
$unwind: "$occurrence"
},
{
$match: { "occurrence.year": { $gte: 1940, $lte: 1960 } }
},
{
$sort: { "occurrence.year": -1 }
},
{
$skip: 1
},
{
$limit: 2
},
{
$group: {
_id: "$_id",
word: { $first: "$word" },
count: { $first: "$count" },
totalWithoutLimitOrOffset: { $first: "$totalWithoutLimitOrOffset" },
occurrence: { $push: "$occurrence" }
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462449.html
標籤:django mongodb 聚合框架 pymongo
上一篇:更新多個陣列檔案中的內部陣列
