我正在用 pymongo 学习 Django。
我有一个 MongoDB 集合,我在其中存储了一些单词以及它们在一些书中的逐年出现次数。
文档以以下格式存储在 MongoDB 中:
{
"_id":{
"$oid":"625c51eec27c99b793074501"
},
"word":"entropy",
"occurrence":13,
"year":{
"1942":[
{
"book":{
"$oid":"625c51eec27c99b7930744f9"
},
"number":8,
"sentence":[
1,
288,
322,
1237,
2570,
2585,
2617,
2634
]
}
],
"1947":[
{
"book":{
"$oid":"625c5280c27c99b793077042"
},
"number":5,
"sentence":[
377,
2108,
2771,
3467,
3502
]
}
]
}
}
现在我想获取_id和特定年份范围查询的带有跳过和限制(以及相应的书 ID)的句子列表。
例如,
这是使用 Django 和 pymongo 的可能任务吗?如果是,最快的方法是什么?
到目前为止,我已经这样做了:
search= {'$and': [{"_id": word_id_obj, "year.1942": {"$exists": 1}}]}
datalist= []
word_docs= wordcollec.find(search, {'year': 1, '_id': 0}).skip(1).limit(5)
sentlist['recordsFiltered']+= wordcollec.count_documents(search)
for b in word_docs:
year_data= b['year'][1942]
for by in year_data:
i= i+1
this_word= {'serial': i, 'year': cyear, 'book': str(by['book'])}
datalist.append(this_word)
但显然,它没有给出预期的结果,因为跳过和限制被应用于根文档对象。年份也有固定值,没有范围。
似乎使用 '$slice' 是一种选择。但我无法弄清楚。
感谢您阅读本文。如果你能发出一些光,还有更多。
这是一种方法:
...获取一个数组,其中每一行将是一个包含“年份”、“书”和“句子”的字典。
db.collection.aggregate([
{ "$set": { "designWorkAround": { "$objectToArray": "$year" } } },
{ "$set": {
"designWorkAround": {
"$map": {
"input": "$designWorkAround",
"as": "yearArray",
"in": {
"year": "$$yearArray.k",
"books": {
"$map": {
"input": "$$yearArray.v",
"as": "bookArray",
"in": {
"bookId": "$$bookArray.book",
"number": "$$bookArray.number",
"sentence": "$$bookArray.sentence"
}
}
}
}
}
}
}
},
{ "$unwind": "$designWorkAround" },
{ "$unwind": "$designWorkAround.books" },
{ "$project": {
"_id": 0,
"year": "$designWorkAround.year",
"book": "$designWorkAround.books.bookId",
"sentence": "$designWorkAround.books.sentence"
}
}
])
在mongoplayground.net上试试。
我不知道您可能想要的所有数据生成或查询,但我可能会重新设计集合,并且每本书都有一个文档,其中包含文档中的所有相关字段。这将使查询、索引等更简单和更有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句