如何在mongodb中$lookup之后使用$project返回嵌套数组

问题描述 投票:0回答:1

我在 MongoDB 中有两个集合,我喜欢使用 $lookup 来映射两个集合并返回特定值。

工作征集

{
    "_id": ObjectId("5b0d2b2c7ac4792df69a9942"),
    "title": "software engineer",
    "categories" : [
        ObjectId("5b0d16ee7ac4792df69a9924"), 
        ObjectId("5b0d47667ac4792df69a9994")
    ],
    "deadline": 2021-05-03T06:29:54.634+00:00
}

job_categories集合:

{
    "_id": ObjectId(5b0d16ee7ac4792df69a9924),
    "name": "front-end"
}
{
    "_id": ObjectId(5b0d47667ac4792df69a9994),
    "name": "full-stack"
}

作业集合

objectid
数组中的
categories
与 job_categories 的
_id
匹配。 如何使用 $lookup 和 $project 返回以下结果。

预期结果:

{
    "_id": ObjectId("5b0d2b2c7ac4792df69a9942"),
    "title": "software engineer",
    "categories" : [
        ObjectId("5b0d16ee7ac4792df69a9924"), 
        ObjectId("5b0d47667ac4792df69a9994")
    ],
    "deadline": 2021-05-03T06:29:54.634+00:00,
    "categories_list": [
        "front-end",
        "full-stack"
    ]
}

预期结果添加一个新字段

categories list
和数组值引用
job_categories
集合的
name
键值。

mongodb mongodb-query aggregation-framework
1个回答
1
投票

直接执行

$lookup
即可。然后
$project
字段
$categories_list.name
categories_list

db.job.aggregate([
  {
    "$lookup": {
      "from": "job_categories",
      "localField": "categories",
      "foreignField": "_id",
      "as": "categories_list"
    }
  },
  {
    "$project": {
      "title": 1,
      "categories": 1,
      "deadline": 1,
      "categories_list": "$categories_list.name"
    }
  }
])

这里是Mongo游乐场供您参考。

© www.soinside.com 2019 - 2024. All rights reserved.