【问题标题】:Mongoose aggregate group items by tagMongoose 按标签聚合分组项目
【发布时间】:2020-08-27 23:44:44
【问题描述】:

我正在尝试按标签对项目进行分组。但我不明白我到底想做什么。

有带有标签的架构项目(_idnametags)是tags_id 的数组(从标签架构中引用)

Item = new Schema({
    id: Schema.ObjectId,
    name: String,
    tags: [ { type: Schema.ObjectId, ref: 'Tag' }]
});

Tag = new Schema({
    id: Schema.ObjectId,
    name: String
});

这是我到目前为止所做的:

Item.aggregate([
        {
          "$lookup": {
            "from": Tag.collection.name,
            "let": { "tags": "$tags" },
            "pipeline": [
              {
                "$match": {
                  "$expr": { "$in": ['$_id', '$$tags'] }
                }
              },
              {
                "$project": {
                  "_id": 1,
                  "name": 1
                }
              }
            ],
            "as": 'tags'
          }
        },
        {
          "$group": {
            "_id": "$tags._id",
            "items": {
              "$push": {
                "id": "$_id",
                "name": "$name",
              }
            }
          }
        }
      ]);

这就是我得到的

{
  "data": [
    {
      "_id": [
        "5eb95e8dcae79713f1de0a27"
      ],
      "items": [
        {
          "id": "5eb95e9fcae79713f1de0a28",
          "name": "My Item 1"
        }
      ]
    },
    {
      "_id": [
        "5eb9564dc4317411fe79e1bf"
      ],
      "items": [
        {
          "id": "5eb95b1430f138131ed90f4f",
          "name": "My Item 2"
        },
        {
          "id": "5eb95ed0cae79713f1de0a29",
          "name": "My Item 3"
        }
      ]
    }
  ]
}

我想获取每个标签的name,而不仅仅是_id,可能不在数组中。在我希望收到的结果下方:

{
  "data": [
    {
      "_id": "5eb95e8dcae79713f1de0a27",
      "name": "My Tag name 1",
      "items": [
        {
          "id": "5eb95e9fcae79713f1de0a28",
          "name": "My Item 1"
        }
      ]
    },
    {
      "_id": "5eb9564dc4317411fe79e1bf",
      "name": "My Tag name 2",
      "items": [
        {
          "id": "5eb95b1430f138131ed90f4f",
          "name": "My Item 2"
        },
        {
          "id": "5eb95ed0cae79713f1de0a29",
          "name": "My Item 3"
        }
      ]
    }
  ]
}

我做错了什么?

【问题讨论】:

    标签: node.js mongoose aggregate


    【解决方案1】:

    解决此问题的一种方法是将标签-name 添加到您的$group 运算符:

    ...
    {
        "$group": {
            "_id": "$tags._id",
            "tagName": {$first: "$tags.name"},
            "items": {
                "$push": {
                    "id": "$_id",
                    "name": "$name",
                }
            }
        }
    }
    ...
    

    请注意,这将获取每个组的第一个匹配条目。另一种选择是使用$replaceRoot$mergeObjects 运算符,就像使用here 一样。

    【讨论】:

    • @Anthony Lee:我的查询中有一个小错误,现在应该修复了。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2018-09-01
    • 2020-05-12
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多