4

I have following json structure -

{
"_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"
        ]
    }]
}

I want to find vmId's if canonical name contains following strings in it- 5b00237d91016cdc38f376bd32d or 5b00237d91016cdc38f376bd31d

My expected output is -

"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. given ids are substring of canonical name i.e. canonical name naa.600605b00237d91016cdc38f376bd32d contains id 5b00237d91016cdc38f376bd32d.

How do I those find documents of which canonical name array contains given substrings??

1 Answer 1

2

Use aggregate and RegExp can handle it.

// 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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.