【问题标题】:MongoDB Filter documents and return only matched subdocument if exists, else null or empty array or empty objectMongoDB过滤文档,如果存在则只返回匹配的子文档,否则为空或空数组或空对象
【发布时间】:2019-01-12 13:24:58
【问题描述】:

我需要在我的项目中实现搜索/过滤。我是 mongodb 的新手。 我需要与名称匹配的所有文档,如果有匹配 sID 的子文档,则只有该子文档应投影到子文档数组中。

但是应该显示匹配名称的两个文档。有没有匹配的子文档都没关系。

我的对象是这样的:

[
        {
            "name" : "abcd",
            "education" : [
                {"sId" : 3233, "sName" : "XYZ"},
                {"sId" : 3244, "sName" : "SIO"}
            ]
        },
        {
            "name" : "abcd",
            "education" : [
                {"sId" : 3254, "sName" : "HDY"},
                {"sId" : 3245, "sName" : "UYT"}
            ]
        },
        {
            "name" : "qwerty",
            "education" : [
                {"sID" : 2212, "sName" : "SKJ"},
                {"sID" : 2133, "sName" : "SKJ"}
            ]
        },
        {
            "name" : "qwerty",
            "education" : [
                {"sID" : 2322, "sName" : "POS"},
                {"sID" : 1122, "sName" : "POS"}
            ]
        }
    ]

当我搜索 {"name": "abcd", "sID": 3244}

那么输出应该是这样的:

[
    {
        "name" : "abcd",
        "education" : [
            {"sId" : 3244, "sName" : "SIO"}
        ]
    },
    {
        "name" : "abcd",
        "education" : []
    }
]

提前致谢。

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    我会使用一个匹配项和带有过滤器的项目,以及你想要匹配元素的查询。

    例子:

    collection.aggregate([ 
    {
        $match: {
        name : "abcd"
        }
    },
    { 
        $project :  {
                name :1,
                education: {
                  $filter: {
                    input: "$education",
                    as: "item",
                    cond: { $eq: [ "$$item.sId", 3244] }
                  }
               }
       }
    }
    ])
    

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 2020-07-03
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      相关资源
      最近更新 更多