创建一个新文档,该文档使用aggregate对具有特定值的字段进行汇总



我有下面的聚合管道。我想做一个像{upvotes : 20, downvotes : 30}这样的文档。我想要一种方法来检查vote字段,如果值是up,将其添加到upvotes字段和down相同,但到downvotes字段。我如何制作那个文档?

 { _id: 57aea6791016c0b023a71e9d,
   review:
    { _id: 57aeb0ee1015118c2b19c8b9,
      updatedAt: Fri Aug 12 2016 22:33:17 GMT-0700 (Pacific Daylight Time),
      createdAt: Fri Aug 12 2016 22:32:30 GMT-0700 (Pacific Daylight Time),
      vote: 'up',
      reviewText: 'test pleas',
      company: 57aea6791016c0b023a71e9d,
      companyName: 'comp1',
      userType: 'anon',
      user: 57aeb0dd1015118c2b19c8b8,
      statements: [Object],
      __v: 0,
      className: '',
      momented: 'a minute ago' } },
 { _id: 57aea6791016c0b023a71e9d,
   review:
    { _id: 57aeb11d3a6bd2cc24b080ad,
      updatedAt: Fri Aug 12 2016 22:33:17 GMT-0700 (Pacific Daylight Time),
      createdAt: Fri Aug 12 2016 22:33:17 GMT-0700 (Pacific Daylight Time),
      vote: 'down',
      reviewText: 'This will hopefully be good',
      company: 57aea6791016c0b023a71e9d,
      companyName: 'comp1',
      userType: 'anon',
      user: 57aeb1033a6bd2cc24b080ac,
      statements: [Object],
      __v: 0,
      className: 'thisUser',
      momented: 'a few seconds ago' } } ]

聚合至今

Comps.aggregate([
    {"$unwind" : "$reviews"},
    {
        "$lookup":{
            "from" : "reviews",
            "localField" : "reviews",
            "foreignField" : "_id",
            "as" : "review"
        }
    },
    { "$unwind": "$review" },
    {$project : {
        review:1
    }}

一个可能的解决方案是使用$cond运算符将"上"/"下"映射到1/0,以便在$分组阶段中易于求和。我认为在当前的聚合管道中添加如下内容应该可以工作:

$group: {
    _id: "$_id",
    upvotes: {$sum: {$cond: [{$eq: ["up", "$review.vote"]}, 1, 0]}},
    downvotes: {$sum: {$cond: [{$eq: ["down", "$review.vote"]}, 1, 0]}}
}

下面是$cond表达式操作符的文档

相关内容

  • 没有找到相关文章

最新更新