如何分组mongoDB并返回结果中的所有字段

Anu*_*ool 4 mongoose mongodb node.js aggregation-framework

我在mongoDB中使用聚合方法进行分组,但是当我使用$group它时,它返回了我用来分组的唯一字段。我已经尝试过了,$project但是也不起作用。我也试过了$first ,但效果很好,但是结果数据现在采用了不同的格式。

我需要的响应格式如下:

{
    "_id" : ObjectId("5b814b2852d47e00514d6a09"),
    "tags" : [],
    "name" : "name here",
    "rating" : "123456789"
}
Run Code Online (Sandbox Code Playgroud)

在我的query.response中添加$ group之后,_id的值将更改。(并且$ group仅接受_id,如果我尝试其他任何关键字,则会引发累加器错误。请也对此进行解释。)

{
    "_id" :"name here" //the value of _id changed to the name field which i used in $group condition
}
Run Code Online (Sandbox Code Playgroud)

我必须删除名称字段中的重复项,而无需更改任何结构和字段。我也将nodeJS与猫鼬一起使用,因此请提供与其兼容的解决方案。

use*_*814 16

您可以使用下面的聚合查询。

$$ROOT保留每个名称的整个文档,然后$replaceRoot将其提升到顶部。

db.col.aggregate([
  {"$group":{"_id":"$name","doc":{"$first":"$$ROOT"}}},
  {"$replaceRoot":{"newRoot":"$doc"}}
])
Run Code Online (Sandbox Code Playgroud)


Sat*_*mar 7

user2683814 的解决方案对我有用,但在我的情况下,当我们替换 newRoot 对象时,我有一个计数器累加器,在最后阶段缺少计数字段,所以我使用$mergeObjects运算符来获取计数字段。

db.collection.aggregate([
 {
  $group: {
    _id: '$product',
    detail: { $first: '$$ROOT' },
    count: {
      $sum: 1,
    },
  },
},
{
  $replaceRoot: {
    newRoot: { $mergeObjects: [{ count: '$count' }, '$detail'] },
  },
}])
Run Code Online (Sandbox Code Playgroud)