查找包含数组中特定值或存在于数组中的文档

时间:2018-08-21 07:28:47

标签: mongodb mongoose mongodb-query aggregation-framework

这里有两个文档,我需要确定数组是否存在"admin",这是$in$exists的最佳方式吗?

{
    "url_name" : "List All Active clients",
    "org_url" : "localhost:4523/create_project/active_clients_list",
    "site_url" : "create_project/active_clients_list",
    "roles" : {
        "writer" : [ 
            "get", 
            "post", 
            "put"
        ],
        "admin" : [ 
            "get", 
            "post", 
            "put"
        ]
    },
    "updated_on" : ISODate("2018-08-21T05:09:25.896Z"),
    "created_on" : ISODate("2018-08-21T05:09:25.896Z")
}, {
    "url_name" : "List All Active clients",
    "org_url" : "localhost:4523/create_project/active_clients_list",
    "site_url" : "create_project/active_clients_list",
    "roles" : {
        "writer" : [ 
            "get", 
            "post", 
            "put"
        ]
    },
    "updated_on" : ISODate("2018-08-21T05:09:34.407Z"),
    "created_on" : ISODate("2018-08-21T05:09:34.407Z")                    
}

考虑这两个文档,我需要找到"admin"存在的文档

1 个答案:

答案 0 :(得分:0)

使用mongoDB $exists查询运算符:

db.collection.find({ "roles.admin": { "$exists": true } })

语法:

{ field: { $exists: <boolean> } }