我们有一个集合,其中有notes个文档,比如:
{
"_id": {
"$oid": "64b42008f622157dd5aead17"
},
"isbn": 9789401466097,
"chapter": 2,
"notes": [
{
"note": "a note",
"dt": 2374238742345,
},
{
"note": "another note about the same book and chapter",
"dt": 2345234234,
}
]
}
和第二个类似的文档(以及更多)
{
"_id": {
"$oid": "64b42234f622157dd5aead1c"
},
"isbn": 9789401466097,
"chapter": 1,
"notes": [
{
"note": "A note about the same book but another chapter",
"dt": 23742387423
},
]
}
{
"_id": {
"$oid": "64b42234f6223de7dd5aead1c"
},
"isbn": 9789401488088,
"chapter": 1,
"notes": [
{
"note": "something about another book",
"dt": 23742384555
},
{
"note": "something else",
"dt": 23452333333
}
}
]
}
其他类似文档可以具有相同或其他isbs或其他chapters.
isbn和chapter的组合形成了文档的唯一密钥.
然后是books个的集合(因此是ISBN).因此,通过以下方式:
collection = 'books' # using pythons pymongo
match = {'$match': {'isbn': isbn}}
projection = {'$project':
{
'_id': '$_id',
'isbn': '$isbn',
'title': '$title',
}
}
pipeline = [
{'$facet':
{
'the_book':
[
match,
projection,
],
}
}
]
我咨询并预测了books件藏品.
我想要做的是用isbn来计算这本书所有章节的所有音符.
我试过的是:
lookup_notes = {'$lookup':
{
'from': 'notes',
'localField': 'isbn',
'foreignField': 'isbn',
'as': 'note',
},
}
project_notes = {'$project':
{
"teller": {
"$size": '$note.notes'
}
}
}
pipeline = [
{'$facet':
{
'the_book':
[
match,
projection,
],
'the_notes':
[
lookup_notes,
match,
project_notes,
],
}
}
]
以及使用$group、$Size和$count的许多其他try .它们导致错误或只计算de notes集合中的相关单据的数量,而不是所有相关单据内的注释的总和.
对于上面的例子,当isbn=9789401466097时,我应该得到结果3,而不是2或5.
谢谢你的帮助.