如何使用mongo在数组中查找子字符串?

时间:2014-11-07 04:42:57

标签: mongodb

我有以下json结构 -

{
"_id" : ObjectId("545c4995e4b031360867fe14"), 
"virtualMachines" : [ 
    {
        "vmId" : "vmx-07",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd31d"
        ]
    }, 
    {
        "vmId" : "vmx-08",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd31d",
            "naa.600605b00237d91016cdc38f376bd32d",
            "naa.600605b00237d91016cdc38f376bd33d"
        ]
    }, 
    {
        "vmId" : "vmx-09",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd34d"
        ]
    }, 
    {
        "vmId" : "vmx-04",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd32d"
        ]
    }]
}

我想找到vmId,如果规范名称中包含以下字符串 - 5b00237d91016cdc38f376bd32d或5b00237d91016cdc38f376bd31d

我的预期输出是 -

"virtualMachines" : [ 
    {
        "vmId" : "vmx-07",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd31d"
        ]
    }, 
    {
        "vmId" : "vmx-08",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd31d",
            "naa.600605b00237d91016cdc38f376bd32d",
            "naa.600605b00237d91016cdc38f376bd33d"
        ]
    }, 
{
        "vmId" : "vmx-04",
        "canonicalName" : [ 
            "naa.600605b00237d91016cdc38f376bd32d"
        ]
    }]

P.S。给定的id是规范名称的子串,即规范名称naa.600605b00237d91016cdc38f376bd32d包含id 5b00237d91016cdc38f376bd32d。

我如何找到规范名称数组包含给定子串的文档?

1 个答案:

答案 0 :(得分:1)

使用汇总 RegExp 可以处理它。

// use regular expression according to needs of searching substring 
var criteria = [ new RegExp("5b00237d91016cdc38f376bd31d$"),
                new RegExp("5b00237d91016cdc38f376bd32d$") ];

var match = {
    $match : {
        "virtualMachines.canonicalName" : {
            $in : criteria
        }
    }
};

db.c.aggregate([ 
    // filter to matched documents
    match, 

    // split virtualMachines array and match again to filter out unmatched items
    {
        $unwind : "$virtualMachines"
    }, 
    match, 

    // reshape virtualMachines array
    {
        $group : {
            _id : "$_id",
            virtualMachines : {
                $push : "$virtualMachines"
            }
        }
    } ]).pretty();