使用 mongoose 与 Mongodb 聚合

Aggregation with Mongodb using mongoose

嘿,我正在尝试使用 moongose 在 mongodb 上进行一些聚合: 我得到了这个数据:

[
  {
    "school": "1",
    "preferences": [
      {
        "person": "X",
        "color": "A"
      },
      {
        "person": "X",
        "color": "B"
      },
      {
        "person": "Y",
        "color": "A"
      }
    ]
  },
  {
    "school": "2",
    "preferences": [
      {
        "person": "Z",
        "color": "A"
      },
      {
        "person": "Y",
        "color": "C"
      }
    ]
  }
]

我认为数据可以自我解释,我想得到的结果是, 当我查询匹配“1”的学校时。我想得到这个结果:

[
  {
    "_id": "X",
    "colors": [
      "A",
      "B"
    ]
  },
  {
    "_id": "Y",
    "colors": ["A"]
  }
]

我以前使用过聚合,但我想不出得到这个结果。

检查这个聚合查询:

db.collectionName.aggregate({
  "$match": {
    "school": "1"
  }
}, {
  "$unwind": "$preferences"
}, {
  "$group": {
    "_id": "$preferences.person",
    "colors": {
      "$addToSet": "$preferences.color" // $addToSet used here only to add distinct color 
    }
  }
})

编辑 如果你想计算 color 的数量,然后使用 sum 的组,如下所示:

db.collectionName.aggregate({
  "$match": {
    "school": "1"
  }
}, {
  "$unwind": "$preferences"
}, {
  "$group": {
    "_id": "$preferences.color",
    "appears": {
      "$sum": 1
    }
  }
})

编辑

根据您的新要求,您应该进行以下聚合:

    db.collectionName.aggregate({
    "$unwind": "$preferences"
},
{
    "$group": {
        "_id": {
            "person": "$preferences.person",
            "color": "$preferences.color"
        },
        "count": {
            "$sum": 1
        }
    }
},
{
    "$group": {
        "_id": "$_id.person",
        "colors": {
            "$push": {
                "color": "$_id.color",
                "count": "$count"
            }
        }
    }
},
{
    "$project": {
        "_id": 0,
        "person": "$_id",
        "colors": 1
    }
}).pretty()