如何过滤嵌套/下级子文档 [英] How to filter a nested/lower subdocument

查看:108
本文介绍了如何过滤嵌套/下级子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的结果,请说:

Say if I have a result like this:

    {
        "_id" : ObjectId("5b722d06c23b5f2bd0329a41"),
        "name" : "test",
        "item" : {
            "_id" : ObjectId("5b722d07c23b5f2bd0329a53"),
            "display_name" : "",
            "image" : "http://via.placeholder.com/700x500/ffffff/000000/?text=No%20Image&",
            "is_private" : true,
            "details" : [
                {
                    "is_private" : false,
                    "type" : "text",
                    "_id" : ObjectId("5b722d06c23b5f2bd0329a44"),
                    "title" : "Name",
                    "content" : "",
                    "order" : 0
                },
                {
                    "is_private" : false,
                    "type" : "text",
                    "_id" : ObjectId("5b722d06c23b5f2bd0329a43"),
                    "title" : "Price",
                    "content" : "",
                    "order" : 1
                },
                {
                    "is_private" : false,
                    "type" : "text",
                    "_id" : ObjectId("5b722d06c23b5f2bd0329a42"),
                    "title" : "Company",
                    "content" : "",
                    "order" : 2
                }
            ],
            "tags" : [ ],
            "__v" : 0
        }
    }

,我想按item.details.is_private过滤,该怎么办?我想返回item的所有属性,但如果它是true

and I want to filter by item.details.is_private, how should I do this? I want to return all properties of item but filter out any item.details.is_private if it is true

我目前将其投影为:

{
    "$project": {
        name: 1,
        item: 1
    }
}

但不确定如何在此设置中实现$filter

but am not sure how to implement $filter in this setting

推荐答案

您可以尝试使用 $filter 聚合

You can try using $addsFields with $filter aggregation

db.collection.aggregate([
  { "$addFields": {
    "item.details": {
      "$filter": {
        "input": "$item.details",
        "as": "detail",
        "cond": {
          "$eq": [ "$$detail.is_private", true ]
        }
      }
    }
  }}
])

这篇关于如何过滤嵌套/下级子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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