如果mongodb中不存在展开字段,如何获得所有结果 [英] How to get all result if unwind field does not exist in mongodb

查看:46
本文介绍了如果mongodb中不存在展开字段,如何获得所有结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从查询下面的集合表单中获取数据:

i am trying to fetch data from collection form below query:

     db.getCollection('jobs').aggregate(
    {$match :{"slug":"bath-room-designer-for-whole-floor-772000"}},
    {$unwind: "$job_activity"},
    {$lookup: {
            "from":"users",
            "localField":"job_activity.user_id",
            "foreignField":"_id",
            "as": "user_details"
        }
    },
    {$unwind: { path: "$user_details", preserveNullAndEmptyArrays: false } },
    {$group: {
                "_id": "$_id", 
                "Job_detail": {"$push": "$job_activity"},
                "job_activity": {"$push": "$job_activity"},
                "user_details": {"$push": "$user_details"}
            }
    }
    
)

但它会导致 $match 集合中存在 datat 的任何地方的空数据,但此 slug 不存在 job_activity

But it result empty data wherever datat exists in the collection for the $match but job_activity is not exist for this slug

谁能帮忙谢谢

推荐答案

使用 $unwind 以保留 job_activity 不存在或为空的文档

use the preserveNullAndEmptyArrays of $unwind to keep documents where job_activity doesn't exist or is empty

所以使用这个 $unwind 阶段:

so use this $unwind stage:

{
  $unwind:
    {
      path: "$job_activity",
      preserveNullAndEmptyArrays: true
    }
}

这篇关于如果mongodb中不存在展开字段,如何获得所有结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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