如何在mongodb中按名称对元素进行分组
我正在使用mongoose和mongo进行一个新项目。我希望返回按不同类别分组的json。我不熟悉aggregate,也不确定它是否适合使用如何在mongodb中按名称对元素进行分组,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我正在使用mongoose和mongo进行一个新项目。我希望返回按不同类别分组的json。我不熟悉aggregate,也不确定它是否适合使用 houseSchema = new mongoose.Schema({ id: Number, name: String, category: String, }); House.aggregate( [ { $group: {
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"
}
}
}
]);
thx@user3100115
House.aggregate(
[
{
$group: {
"_id": {
"category": "$category",
},
"names": {
"$addToSet": "$name"
}
}
}
]);
使用
“name”:{$addToSet:“$name”}
异常:无效运算符\'$addToSet\'我会看看这个!使用“name”:{$addToSet:“$name”}
异常:无效运算符\'$addToSet\'我会看看这个!