[英]How to sum the values from a field in subdocuments from an array?
如何從提供的任何關鍵字中僅投影在每個文檔中找到的單詞? 文件結構如下:
{
_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'
}
}
}
])
我想要做的不是投影整個字典,我只想投影每個文檔的匹配單詞及其計數。 當然,我希望每個文檔的字典位於單獨的投影文檔中。 有沒有辦法做到這一點?
使用$filter
過濾您的 arrays,試試這個:
let keywords = ['word2', 'word3']
db.collection.aggregate([
{
$project: {
_id: 0,
dictionary: {
$filter: {
input: "$dictionary",
as: "word",
cond: {
$in: ["$$word.word", keywords]
}
}
}
}
},
{
$match: {
$expr: {
$gt: [{ $size: "$dictionary" }, 0]
}
}
}
]);
Output:
/* 1 */
{
"dictionary" : [
{
"word" : "word2",
"count" : 5
}
]
},
/* 2 */
{
"dictionary" : [
{
"word" : "word2",
"count" : 6
},
{
"word" : "word3",
"count" : 3
}
]
},
/* 3 */
{
"dictionary" : [
{
"word" : "word3",
"count" : 2
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.