【发布时间】:2021-06-12 15:04:42
【问题描述】:
如何从提供的任何关键字中仅投影在每个文档中找到的单词?文档结构如下:
{
_id: 24752893,
dictionary: [
{
word: 'word1',
count: 2,
},
{
word: 'word2',
count: 5,
},
{
word: 'word4',
count: 1,
},
....
]
},
{
_id: 6786765789,
dictionary: [
{
word: 'word4',
count: 3,
},
{
word: 'word2',
count: 6,
},
{
word: 'word3',
count: 3,
},
{
word: 'word5',
count: 1,
},
....
]
},
........
{
_id: 76675567,
dictionary: [
{
word: 'word1',
count: 7,
},
{
word: 'word3',
count: 2,
},
....
]
}
如果给出了像 ['word2', 'word3'] 这样的关键字列表,并且只要在其中找到关键字列表中的任何单词,就应该检索文档。我已经编写了这个聚合管道来获取必要的文档:
client.database.collection.aggregate([
{
'$project': {
'_id': 1,
'dictionary': {
'$filter': {
'input': '$dictionary',
'as': 'words',
'cond': {
'$in': [
'$$words.word', keywords
]
}
}
},
}
},
{
'$match': {
'dictionary': {
'$ne': []
}
}
},
,
{
'$unwind': '$dictionary'
},
{
'$group': {
'_id': '$_id',
'score': {
'$sum': '$dictionary.count'
}
}
}
])
我想要做的不是投影整个字典,我只想投影每个文档的匹配单词及其计数。当然,我希望每个文档的字典位于单独的投影文档中。有没有办法做到这一点?
【问题讨论】:
标签: arrays mongodb mongodb-query aggregation-framework pymongo