MongoDB根据子对象的键过滤出子对象

时间:2019-11-20 13:00:19

标签: mongodb mongoose mongodb-query

有一个具有以下架构的MongoDB对象,其中的键(key1,key2,key3可以是动态的,因此 手动查询不是解决方案)

{
"_id" : <docID>,
"user" : <userID>,
"key1" : {
    "priorityLevel" : "p0",
    "filled" : false,
    "category" : "Basic",
    "fieldType" : "input"
},
"key2" : {
    "priorityLevel" : "p1",
    "filled" : false,
    "category" : "Basic",
    "fieldType" : "input"
},
"key3" : {
    "priorityLevel" : "p0",
    "filled" : false,
    "category" : "Basic",
    "fieldType" : "input"
}
}

现在,预期的输出是过滤出 priorityLevel = p0 的键,并将输出显示为

{
"_id" : <docID>,
"user" : <userID>,
"key1" : {
    "priorityLevel" : "p0",
    "filled" : false,
    "category" : "Basic",
    "fieldType" : "input"
},
"key3" : {
    "priorityLevel" : "p0",
    "filled" : false,
    "category" : "Basic",
    "fieldType" : "input"
}
}

任何帮助将不胜感激。 谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用$objectToArray在您的$$ROOT上应用$filter。然后,您需要$arrayToObject$replaceRoot才能恢复到原始形状,请尝试:

db.collection.aggregate([
    {
        $project: {
            fields: {
                $filter: {
                    input: { $objectToArray: "$$ROOT" },
                    cond: { 
                        $or: [ 
                            { $ne: [{ $type: "$$this.v" }, "object" ] },
                            { $eq: [ "$$this.v.priorityLevel", "p0" ] }
                        ] 
                    }
                }
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$fields" }
        }
    }
])

Mongo Playground