Mongodb - regex match of keys for subdocuments

大城市里の小女人 提交于 2019-11-30 03:48:41

问题


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


回答1:


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).



来源:https://stackoverflow.com/questions/7278417/mongodb-regex-match-of-keys-for-subdocuments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!