【问题标题】:How to group element by name in mongodb如何在mongodb中按名称对元素进行分组
【发布时间】:2015-07-01 02:22:10
【问题描述】:

我在一个新项目中使用 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' } } ]

【问题讨论】:

  • 使用"name": {$addToSet: "$name"}
  • 异常:无效的操作符\'$addToSet\' 我会看看这个!

标签: mongodb mongoose aggregation-framework


【解决方案1】:

谢谢@user3100115

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2020-12-28
    • 2020-08-07
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多