首页 > 解决方案 > MongoDb中嵌套数组内的条件检查

问题描述

经过几个管道阶段后,我想出了以下示例结果,这是一个文档。如果videos.views.userId包含10,我需要指出videos.isWatched = true其他false。我们可以使用$unwind,检查条件,然后group它。

这是示例输出,原始文档包含很多字段,所以我只想用更少的代码来做,除非我需要unwind有什么办法可以不用 unwind("videos")吗?

[
    {
        "_id":"someId",
        "videos":[
            {
                "_id":"1",
                "name":"A",
                "views":[
                    {
                        "userId":10,
                        "group":"X"
                    }
                ]
            },
            {
                "_id":"2",
                "name":"B",
                "views":[
                    {
                        "userId":20,
                        "group":"Y"
                    }
                ]
            }
        ],
        "Assessment":[
            {
                "_id":"22",
                "title": "Hello world"
            }
        ]
    }
]

预期结果

[
    {
        "_id":"someId",
        "videos":[
            {
                _id:"1",
                name:"A",
                views:[
                    {
                        userId:10,
                        group:"X"
                    }
                ],
                "isWatched":true
            },
            {
                _id:"2",
                name:"B",
                views:[
                    {
                        userId:20,
                        group:"Y"
                    }
                ],
                "isWatched":false
            }
        ],
        "Assessment":[
            {
                _id:"22",
                title: "Hello world"
            }
        ]
    }
]

标签: mongodbaggregation-framework

解决方案


您可以使用$map$mergeObjects将新字段添加到现有数组。$anyElementTrue可用于确定是否有任何userId等于10

db.collection.aggregate([
    {
        $addFields: {
            videos: {
                $map: {
                    input: "$videos",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { 
                                isWatched: {
                                    $anyElementTrue: {
                                        $map: { input: "$$this.views", in: { $eq: [ "$$this.userId", 10 ] } }
                                    }
                                }  
                            }
                        ]
                    }
                }
            }
        }
    }
])

蒙戈游乐场


推荐阅读