我想根据特定值对文档进行分组。我还需要选择的键。Mongo DB组记录并返回所选字段
这里是我的文档:
{
title: "Add 1",
userId: 1,
description: "this is add 1",
location: {
city: "Newyork",
address: "Street 1, Flat # 40"
},
createdAt: "2015-10-20",
title: "Add 2",
userId: 1,
description: "this is add 2",
location: {
city: "Paris",
address: "Street 2, Flat # 80"
},
createdAt: "2015-10-22",
title: "Add 3",
userId: 1,
description: "this is add 3",
location: {
city: "Newyork",
address: "Street 5, Flat # 58"
},
createdAt: "2015-10-23"
}
我想组文件由location.city
。我也只需要标题和位置。
以上情况应该查询什么?
我曾尝试此查询:
Adds.aggregate([
{ $match: { userId: params.userId } },
{ $group: { _id: "$location.city" } },
]);
上述查询只返回location.city,我想要的位置&冠军的完整的对象。
你可以把它用.aggregate如果这个数据是在一个数组分解做。不是一个单一的文件。 – Tiramisu
@Tiramisu我已经尝试使用聚合,但响应结果不好。我使用location.city对记录进行分组,因此它只返回location.city。请检查更新的问题 – StormTrooper