如何对mongoDB进行分组并返回结果中的所有字段 [英] how to group in mongoDB and return all fields in result

查看:885
本文介绍了如何对mongoDB进行分组并返回结果中的所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using aggregate method in mongoDB to group but when I use $group it returns the only field which I used to group. I have tried $project but it is not working either. I also tried $first and it worked but the result data is now in different format.

我需要的响应格式如下:

The response format I need looks like:

{
    "_id" : ObjectId("5b814b2852d47e00514d6a09"),
    "tags" : [],
    "name" : "name here",
    "rating" : "123456789"
}

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

and after adding $group in my query.response is like this, the value of _id changes. (and the $group is taking only _id, if i try any other keyword it throws an error of accumulator something. please explain this also.)

{
    "_id" :"name here" //the value of _id changed to the name field which i used in $group condition
}

我必须删除名称字段中的重复项,而无需更改任何结构和字段.我也将nodeJS和mongoose一起使用,因此请提供适用于它的解决方案.

I have to remove the duplicates in name field, without changing any structure and fields. also I am using nodeJS with mongoose, so please provide the solution that works with it.

推荐答案

您可以使用以下聚合查询.

You can use below aggregation query.

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

$$ROOT to keep the whole document per each name followed by $replaceRoot to promote the document to the top.

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

这篇关于如何对mongoDB进行分组并返回结果中的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆