MongoDB查找subDocument _ids喜欢“string”的所有子文档

时间:2015-10-10 05:40:16

标签: mongodb mongodb-query aggregates

示例文档结构如下:

{
    "_id" : "https://docs.mongodb.org/manual",
    "collection" : {
        "_id" : "collection",
        "urls" : [ 
            "https://docs.mongodb.org/manual/c1", 
            "https://docs.mongodb.org/manual/c2"
        ]
    },
    "collectionNew" : {
        "_id" : "collection1",
        "urls" : [ 
            "https://docs.mongodb.org/manual/c1New", 
            "https://docs.mongodb.org/manual/c2New"
        ]
    },
    "log" : {
        "_id" : "log",
        "urls" : [ 
            "https://docs.mongodb.org/manual/l1", 
            "https://docs.mongodb.org/manual/l2"
        ]
    }
}

我的收藏中有多个这样的文件。 找到文件后

db.AutoSearch.find({"_id": "https://docs.mongodb.org/manual"})

我想在其下搜索名称为“collection”

的所有子文档

我将文档结构更改为:

{
"_id" : "https://docs.mongodb.org/manual",
"contents" : [ 
    {
        "_id" : "connect",
        "urls" : [ 
            "https://docs.mongodb.org/manual/search/?query=connect"
        ]
    }, 
    {
        "_id" : "connection",
        "urls" : [ 
            "https://docs.mongodb.org/manual/search/?query=connection", 
            "https://docs.mongodb.org/manual/search/?query=connection%20pymongo"
        ]
    }
    {
        "_id" : "list",
        "urls" : [ 
            "https://docs.mongodb.org/manual/search/?query=listfiles", 
            "https://docs.mongodb.org/manual/search/?query=listdatabases", 
            "https://docs.mongodb.org/manual/search/?query=listcommands"
        ]
    }, 
    {
        "_id" : "log",
        "urls" : [ 
            "http://docs.mongodb.org/manual/tutorial/rotate-log-files/", 
            "http://docs.mongodb.org/manual/reference/log-messages/"
        ]
    }, 
    {
        "_id" : "index",
        "urls" : [ 
            "https://docs.mongodb.org/manual/search/?query=index-related%20commands"
        ]
    }
]}

然后使用mongoDB aggregate query

db.AutoSearch.aggregate([{$match:{ "_id": "https://docs.mongodb.org/manual"}}, 
                    {$unwind: '$contents'},
                    {$match:{"contents._id":/connect/}}])

我得到了所需的输出。

0 个答案:

没有答案