我正在为一个新项目使用mongoose和mongo。我希望返回按不同类别分组的json。我不熟悉聚合,也不确定它是否是正确的使用方法。
houseSchema = new mongoose.Schema({
id: Number,
name: String,
category: String,
});
House.aggregate(
[
{
$group: {
"_id": {
"category": "$category",
"name": "$name"
}
}
}
]);
//results
[ { _id: { category: 'a', name: 'name1' } },
{ _id: { category: 'a', name: 'name2' } },
{ _id: { category: 'a', name: 'name3' } },
{ _id: { category: 'b', name: 'name4' } },
{ _id: { category: 'b', name: 'name5' } },
{ _id: { category: 'b', name: 'name6' } },
{ _id: { category: 'b', name: 'name7' } },
{ _id: { category: 'c', name: 'name8' } },
{ _id: { category: 'c', name: 'name9' } } ]
我想要这种
[ { _id: { category: 'a', name: ['name1', 'name2', 'name3'] } },
{ _id: { category: 'b', name: ['name4', 'name5', 'name6', 'name7'] } },
{ _id: { category: 'c', name: ['name8', 'name9' } } ]
thx@user3100115
House.aggregate(
[
{
$group: {
"_id": {
"category": "$category",
},
"names": {
"$addToSet": "$name"
}
}
}
]);