如何在 mongodb 中 $lookup 后使用 $project 返回嵌套数组 [英] how to use $project return nest array after $lookup in mongodb

查看:149
本文介绍了如何在 mongodb 中 $lookup 后使用 $project 返回嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two collections in MongoDB and I like to use $lookup to mapping two collections and return specific values.

作业集

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

job_categories 集合:

job_categories collection:

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

作业集合categories 数组中的objectid 匹配job_categories 的_id.如何使用 $lookup 和 $project 返回如下结果.

The objectidin job collection categories array matches the _id of job_categories. how to use $lookup and $project to return the following result.

预期结果:

{
    "_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键值.

The expected result adds a new filed categories list and the array value reference job_categories collection's namekey value.

推荐答案

直接执行 $lookup 即可.然后将 $project 字段 $categories_list.name 设为 categories_list.

Just perform the $lookup directly. Then $project the field $categories_list.name as categories_list.

这是 Mongo 游乐场供您参考.

这篇关于如何在 mongodb 中 $lookup 后使用 $project 返回嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆