mongoose 如何在mongodb中过滤查找聚合查询中的嵌套数组

hmmo2u0o  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(175)
db.magazine.aggregate([
        {
            $lookup: {
                from: 'pages',
                localField: 'typeId',
                foreignField: 'visibleTo._id',
                as: 'List'
            }
        }
    ])

这里我在'visbleTo'字段中有一个嵌套数组。当我查找pages集合时。现在我从'visibleTo'字段中获取所有对象。这里我必须只筛选'visibleTo._id'中的匹配对象。
这是我目前的成绩

{ 
    "_id" : ObjectId("635f6e6902698132d9659c5a"), 
    "name" : "Sports Magazine", 
    "typeId" : ObjectId("635fc99652ecf9a969eed777"),
    "List" : [
        {
            "_id" : ObjectId("63748c1241ccfbc85a49af20"), 
            "pagename" : "cover", 
            "visibleTo" : [
                {
                    "checked" : "No", 
                    "name" : "Media",
                    "_id" : ObjectId("635fc99652ecf9a969eed777")
                }, 
                {
                    "checked" : "Yes",
                    "name" : "GHS", 
                    "_id" : ObjectId("635fc99652ecf9a969eed77c")
                }
            ]
        }, 
        {
            "_id" : ObjectId("637493810ca44ad4d564e7b3"), 
            "pagename" : "back", 
            "visibleTo" : [
                {
                    "checked" : "Yes",  
                    "name" : "Media",
                    "_id" : ObjectId("635fc99652ecf9a969eed777")
                }, 
                {
                    "checked" : "Yes", 
                    "name" : "GHS", 
                    "_id" : ObjectId("635fc99652ecf9a969eed77c")
                }, 
                {
                    "checked" : "Yes", 
                    "name" : "Others",
                    "_id" : ObjectId("635fc99652ecf9a969eed781")
                }
            ],
        }
    ]
}
nukf8bse

nukf8bse1#

这里有几种方法。我采用的方法是利用$lookup5.0)中嵌套的pipeline的功能。具体来说,我添加了一个$filter,以便在检索visibleTo数组时将不需要的条目从其中删除。$lookup的新增功能包括:

let: {
        typeId: "$typeId"
      },
      pipeline: [
        {
          "$addFields": {
            "visibleTo": {
              "$filter": {
                "input": "$visibleTo",
                "cond": {
                  $eq: [
                    "$$this._id",
                    "$$typeId"
                  ]
                }
              }
            }
          }
        }
      ]

Full playground example here

相关问题