如何在 mongoDB 中分组并返回结果中的所有字段 [英] how to group in mongoDB and return all fields in result
问题描述
我在 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 和猫鼬,所以请提供适用的解决方案.
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屋!