MongoDB-正则表达式子文档的密钥匹配 [英] Mongodb - regex match of keys for subdocuments

查看:78
本文介绍了MongoDB-正则表达式子文档的密钥匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些保存在集合中的文档(称为urls),如下所示:

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'
        }
    }
}

使用mongo CLI,是否可以查找与/^url_/匹配的payload子文档?并且,如果可能的话,是否还可以查询匹配项的子文档(例如,确保text存在)?

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

我在想这样的事情:

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

但这将返回0个结果.

任何帮助或建议都很好.

Any help or suggestions would be great.

谢谢

马特

推荐答案

无法以这种方式针对文档密钥进行查询.您可以使用$exists搜索精确匹配,但是找不到与模式匹配的键名.

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.

我假设(也许是错误地)假设您正在尝试查找具有URL子文档的文档,并且不是所有文档都具有此功能?为什么不将类型信息下推到某个级别,例如:

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", ...})

如果我没有注意到您不应该在MongoDB中使用点号(.)作为键名,我也会感到失落.在某些情况下,可以创建这样的文档,但是当您尝试查询嵌入式文档时,这会造成很大的混乱(可以这么说,Mongo使用点作为路径分隔符".)

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

这篇关于MongoDB-正则表达式子文档的密钥匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆