Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - regex match of keys for subdocuments

I have some documents saved in a collection (called urls) that look like this:

{
    payload:{
        url_google.com:{
            url:'google.com',
            text:'search'
        }
    }
},
{
    payload:{
        url_t.co:{
            url:'t.co',
            text:'url shortener'
        }
    }
},
{
    payload:{
        url_facebook.com:{
            url:'facebook.com',
            text:'social network'
        }
    }
}

Using the mongo CLI, is it possible to look for subdocuments of payload that match /^url_/? And, if that's possible, would it also be possible to query on the match's subdocuments (for example, make sure text exists)?

I was thinking something like this:

db.urls.find({"payload":{"$regex":/^url_/}}).count();

But that's returning 0 results.

Any help or suggestions would be great.

Thanks,

Matt

like image 609
Matt P Avatar asked Sep 02 '11 01:09

Matt P


1 Answers

It's not possible to query against document keys in this way. You can search for exact matches using $exists, but you cannot find key names that match a pattern.

I assume (perhaps incorrectly) that you're trying to find documents which have a URL sub-document, and that not all documents will have this? Why not push that type information down a level, something like:

{
  payload: {
    type: "url",
    url: "Facebook.com",
    ...
  }
}

Then you could query like:

db.foo.find({"payload.type": "url", ...})

I would also be remiss if I did not note that you shouldn't use dots (.) is key names in MongoDB. In some cases it's possible to create documents like this, but it will cause great confusions as you attempt to query into embedded documents (where Mongo uses dot as a "path separator" so to speak).

like image 112
dcrosta Avatar answered Sep 30 '22 09:09

dcrosta