如何过滤子文档的属性聚合?

时间:2017-07-07 14:39:01

标签: mongodb database nosql

我目前在SaltStack上使用MongoDB作为返回后端,我需要查询数据库,例如获取失败作业的步骤列表,每个jobReturn都是这样的对象(这里是它的一部分) ):

{
    "_id" : ObjectId("595d12c99fee8e5d23f344a8"),
    "fun" : "state.apply",
    "jid" : "20170705162344866073",
    "return" : {
        "svn_|-Template tideway should have the revision HEAD active for the staging environment (Live)_|-http://svn-svc-xxx-es/staging/xxx-template-tideway/trunk_|-latest" : {
            "comment" : "Checked out revision 456.",
            "name" : "http://svn.svc.xxx.es/staging/xxx-template-tideway/trunk",
            "start_time" : "18:24:13.939000",
            "result" : true,
            "duration" : 752.0,
            "__run_num__" : 35,
            "changes" : {
                "new" : "http://svn.svc.xxx.es/staging/xxx-template-tideway/trunk",
                "revision" : "456\r"
            },
            "__id__" : "Template tideway should have the revision HEAD active for the staging environment (Live)"
        },
        "win_dacl_|-The application user should have full access to the application directories_|-C:\\inetpub\\wwwroot_|-present" : {
            "comment" : "",
            "name" : "C:\\inetpub\\wwwroot",
            "start_time" : "18:24:39.668000",
            "result" : true,
            "duration" : 7.0,
            "__run_num__" : 61,
            "changes" : {},
            "__id__" : "The application user should have full access to the application directories"
        },
        "svn_|-Template capucine should have the revision HEAD active for the staging environment (Live)_|-http://svn-svc-xxx-es/staging/xxx-template-capucine/trunk_|-latest" : {
            "comment" : "Checked out revision 456.",
            "name" : "http://svn.svc.xxx.es/staging/xxx-template-capucine/trunk",
            "start_time" : "18:24:07.544000",
            "result" : true,
            "duration" : 673.0,
            "__run_num__" : 23,
            "changes" : {
                "new" : "http://svn.svc.xxx.es/staging/xxx-template-capucine/trunk",
                "revision" : "456\r"
            },
            "__id__" : "Template capucine should have the revision HEAD active for the staging environment (Live)"
        },
        .....
    }
}

例如,我需要获取此对象,但所有“return”对象都有“result”:false

我尝试使用$project但它只在列表上工作。

我无法修改应用程序放置数据的方式。我同意在这个模式中,对象列表将是更好的解决方案。

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

我在MongoDB 3.4.4 +中找到了使用$objectToArray表达式的解决方案:

db.saltReturns.aggregate([
    { $match: { "fun": { $eq: "state.apply" }}},
    { $project: {
        matches: {
            $filter: {
                input: { $objectToArray: "$return" },
                as: "return",
                cond: { $eq: ["$$return.v.result", true] }
            }
        }
    }}
])