我不会返回使用的单词列表和总分数列表。
我的文档就像这样
"negativeWords" : [
"Angry"
],
"positiveWords" : [
"Happy"
],
每个文档都可以有多个否定或肯定的单词。
每个文档的总得分如下:
"overall" : 3,
我希望获得如下数组:
words : [Angry, Happy, Sad, bad, excited]
每个文档的总得分数组:
总的来说:[4,3,2,5,]我不知道如何获得两者。
Review.aggregate([
//now I want to get the overall scores and the array of words
{
$project: {
arr : {"$setUnion" : ["$negativeWords", "$positiveWords"]},
overallScores : "$overall"
}
},
{
$unwind : "$arr"
},
{
$group : {
_id : "$_id",
words : {$push : "$arr"},
overallScores : {$first : "$overallScores"}
}
},
编辑: 现在我输出到了这里。我想得到数组:
[ { _id: 5898b02c1321831b84740320,
words: [ 'Angry', 'Happy' ],
overallScores: 3 },
{ _id: 5898b02c1321831b8474031f,
words:
[ 'Difficult',
'Easy returns',
'Afordable',
'Great products',
'Good service' ],
overallScores: 5 },
{ _id: 5898b02c1321831b8474031e,
words:
[ 'Difficult',
'Easy returns',
'Afordable',
'Great products',
'Good service' ],
overallScores: 5 },
{ _id: 5898b02c1321831b8474031d,
words: [ 'Caring', 'Easy returns', 'Bad', 'Expensive' ],
overallScores: 3 },
{ _id: 5898b02c1321831b8474031c,
words: [ 'Difficult', 'Afordable', 'Awesome' ],
overallScores: 4 },
{ _id: 5898b02c1321831b8474031b,
words: [ 'Bad', 'Respect', 'Rude', 'Expensive', 'Disgusted' ],
overallScores: 3 },
{ _id: 5898b02c1321831b8474031a,
words: [ 'Difficult', 'Afordable' ],
overallScores: 4 },
{ _id: 5898b02c1321831b84740319,
words: [ 'No refund', 'Respect' ],
overallScores: 3 } ]
代码:
{
$project: {
arr : {"$setUnion" : ["$negativeWords", "$positiveWords"]},
overallScores : "$overall"
}
},
{
$unwind : "$arr"
},
{$unwind : "$overallScores"},
{
$group : {
_id : "$_id",
words : {$push : "$arr"},
overallScores : {$first : "$overallScores"}
}
}
答案 0 :(得分:0)
以下是一种方法,无需担心使用$unwind
:
$group : {
_id: null,
words: {
$addToSet: {
$setUnion: ["$negativeWords", "$positiveWords"]
},
},
overallScores: {
$push: "$overall"
},
}
$project : {
_id: 0,
overallScores: 1,
words: {
$reduce: {
input: '$words',
initialValue: [],
in : {
$setUnion: ['$$value', '$$this']
}
},
}
}