0

I want to get documents having a particular key in its sub-document using regex. I had a look at the following post: " Mongodb - regex match of keys for subdocuments ", but since it was answered more than 8 years ago, is there any update on the question? Is it possible to do this now?

my collection is similar to one below :

{
    item : a,
    payload:{
        url_google.com:1,
        url_apple.com:1
    }
},
{
    item : b,
    payload:{
        url_t.co:1,
        t.co:1
    }
},
{
    item : c,
    payload:{
        google.com:2,
        facebook.com:2
    }
}

and I want to get all those documents having at least one of the keys of payload that contain 'url' in them. In the above case, the query would return

{
    item : a,
    payload:{
        url_google.com:1,
        url_apple.com:1
    }
},
{
    item : b,
    payload:{
        url_t.co:1,
        t.co:1
    }
}

1 Answers1

0

It is possible, yes.

You can use $objectToArray, like

db.collection.aggregate([
    {$addFields:{
          payload_array: {$objectToArray: "$payload"}
    }},
    {$match:{
          "payload_array.k": {$regex: "^url_"}
    }},
    {$project:{ payload_array:0 }}
])

Playground

Note that because the selection occurs after modifying the input document, this query will not be able to use an index, so every time it runs will be a collection scan.

Joe
  • 25,000
  • 3
  • 22
  • 44