如何在mongodb中按名称对元素进行分组

时间:2015-06-30 17:22:54

标签: mongodb mongoose aggregation-framework

我正在使用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' } } ]

1 个答案:

答案 0 :(得分:0)

thx @ user3100115

House.aggregate(
        [
            {
                $group: {
                    "_id": {
                          "category": "$category",
                    },
                    "names": {
                          "$addToSet": "$name"
                    }
                }
            }
        ]);