【问题标题】:trying to return 2 arrays with mongo aggregate尝试使用 mongo 聚合返回 2 个数组
【发布时间】:2017-06-25 10:06:29
【问题描述】:

我不会返回使用的单词列表和总分列表。

我的文档中有这样的

   "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"}
    }
}

【问题讨论】:

  • 整个字段与数组有什么关系?
  • 总的来说只是一个数字。它们与 positiveWords 和negativeWords 数组无关。

标签: node.js mongodb aggregation-framework


【解决方案1】:

这是一种不用担心使用$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']
            }
        },
    }
}

【讨论】:

  • 感谢您的回复,但 $reduce 适用于 3.4 版。我有 3.2 。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
  • 2017-08-31
  • 2020-05-02
  • 2011-04-15
  • 2020-11-06
  • 1970-01-01
相关资源
最近更新 更多