我想根據特定值對文檔進行分組。我還需要選擇的鍵。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