MongoDB查询数组,仅返回包含值

时间:2018-07-23 01:40:40

标签: mongodb mongoose

我在MongoDB上具有以下菜单集合。它具有Permission和Submenu之类的值。

{ 
    "_id" : ObjectId("5b42c5c8a80e160a146822e1"), 
    "HasSubmenu" : "false", 
    "Icon" : "fas fa-home", 
    "MenuCode" : "PaginaInicial", 
    "MenuName" : "Página Inicial", 
    "MenuState" : "paginainicial", 
    "Permission" : 1
    "Submenu" : [ ], 
},
{ 
    "_id" : ObjectId("5b42c5c8a80e160a146822e2"), 
    "HasSubmenu" : "true", 
    "Icon" : "far fa-file-alt", 
    "MenuCode" : "FormulariosApoio", 
    "MenuName" : "Formularios de Apoio", 
    "MenuState" : "",
    "Permission" : 1
    "Submenu" : [
        {
            "MenuState" : "tiposassociados", 
            "MenuName" : "Tipos Associados", 
            "MenuCode" : "TiposAssociados", 
            "Icon" : "fas fa-tags", 
            "HasSubmenu" : false, 
            "Permission" : 1
        }, 
        {
            "MenuState" : "naturalidades", 
            "MenuCode" : "Naturalidade", 
            "MenuName" : "Naturalidade", 
            "Icon" : "fas fa-globe-asia", 
            "HasSubmenu" : false, 
            "Permission" : 4
        }, 
        {
            "MenuState" : "nacionalidades", 
            "MenuCode" : "Nacionalidade", 
            "MenuName" : "Nacionalidade", 
            "Icon" : "fas fa-globe-americas", 
            "HasSubmenu" : false, 
            "Permission" : 4
        },     
    ]

}

我需要返回帮助,只有菜单和子菜单具有{“ Permission”:1}的值,即使菜单没有任何子菜单

尝试过此方法,但确实无法正常工作。

db.getCollection("menus").find({
     $and: [
        {"Submenu" : { $elemMatch : {"Permission": 1}}},
        {"Permission": 1},
     ]   
});

1 个答案:

答案 0 :(得分:1)

您可以尝试进行$filter聚合

db.collection.aggregate([
  { "$match": { "Permission": 1 } },
  { "$addFields": {
    "Submenu": {
      "$filter": {
        "input": "$Submenu",
        "as": "submenu",
        "cond": {
          "$eq": [ "$$submenu.Permission", 1 ]
        }
      }
    }
  }}
])