【问题标题】:How to perform $group and $lookup aggregations together如何同时执行 $group 和 $lookup 聚合
【发布时间】:2021-11-09 13:36:47
【问题描述】:

这里有两个收藏。

我想通过执行$group 聚合或任何其他方法在数组中获取发布者详细信息。

书籍

[
   {
      "_id":8751,
      "title":"The Banquet",
      "author":"AB",
      "copies":2,
      "publisher":[
         1,
         2
      ]
   },
   {
      "_id":8752,
      "title":"Divine Comedy",
      "author":"Dante",
      "copies":1,
      "publisher":[
         3,
         1
      ]
   }
]

出版商

[
   {
      "id":1,
      "name":"p 1"
   },
   {
      "id":2,
      "name":"p 2"
   },
   {
      "id":3,
      "name":"p 3"
   },
   {
      "id":4,
      "name":"p 4"
   }
]

我已尝试使用以下查询,但结果不是预期的。

    db.books.aggregate([
      {
        "$unwind": "$publisher"
      },
      {
        "$group": {
          "_id": "$publisher",
          
        }
      },
      {
        "$lookup": {
          "from": "publisher",
          "localField": "_id",
          "foreignField": "id",
          "as": "publishers"
        }
      }
    ])

预期输出

[
   {
      "id":1,
      "name":"p 1"
   },
   {
      "id":2,
      "name":"p 2"
   },
   {
      "id":3,
      "name":"p 3"
   }
]

如何获取数组中的出版商列表

【问题讨论】:

  • 你是什么意思出版商列表中的书籍?在预期的输出中没有数组。您可以将数组字段与单个字段连接,如果数组包含该元素,它们将匹配。

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您可以使用此聚合查询:

  • 首先$lookup 使用publisher 数组。是的,您可以使用数组来连接值。
  • 然后是$unwind$lookup返回的数组。
  • $group by id 删除重复捕获$first 值的名称。
  • 然后,(可选)使用$project 输出id 而不是_id
  • 和(可选)$sort by id
db.Books.aggregate([
  {
    "$lookup": {
      "from": "Publisher",
      "localField": "publisher",
      "foreignField": "id",
      "as": "publishers"
    }
  },
  {
    "$unwind": "$publishers"
  },
  {
    "$group": {
      "_id": "$publishers.id",
      "publisher": {
        "$first": "$publishers.name"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "id": "$_id",
      "publisher": 1
    }
  },
  {
    "$sort": {
      "id": 1
    }
  }
])

例如here

请注意,没有“可选”阶段的输出是这样的

[
  {
    "_id": 1,
    "publisher": "p 1"
  },
  {
    "_id": 3,
    "publisher": "p 3"
  },
  {
    "_id": 2,
    "publisher": "p 2"
  }
]

以及查询的所有阶段:

[
  {
    "id": 1,
    "publisher": "p 1"
  },
  {
    "id": 2,
    "publisher": "p 2"
  },
  {
    "id": 3,
    "publisher": "p 3"
  }
]

【讨论】:

    【解决方案2】:

    如果我理解正确,您想将 publisher 数组中的数字替换为发布者集合中的文档。您可以使用$lookup 聚合管道简单地做到这一点:

    db.books.aggregate([
      {
        "$lookup": {
          "from": "publisher",
          "localField": "publisher",
          "foreignField": "id",
          "as": "publishers"
        }
      }
    ])
    

    Working example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 2017-05-12
      • 2019-09-03
      • 2020-10-05
      • 2020-04-03
      • 2019-01-21
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多