MongoDB查询-限制名称与模式匹配的字段 [英] MongoDB Query - limit fields where name matches pattern
问题描述
我已经阅读了有关MongoDB中Projection的所有内容.我希望这很简单,但是由于Mongo查询具有压倒性的灵活性,我只是想念它.
I've read everything I can find about Projection in MongoDB. I'm hoping this is simple and I just missed it due to the overwhelming flexibility of Mongo queries.
在MySql数据库中,我们采用了一种商业惯例,即隐藏"字段以下划线作为前缀.我们的应用程序知道如何隐藏这些字段.
In our MySql database, we've adopted a business practice of having "hidden" fields be prefixed with an underscore. Our application knows how to hide these fields.
将一些数据移动到mongo,我需要检索文档,所有下划线前缀字段均省略.当然,这应该在查询中完成,而不要在检索后进行文档处理.
Moving some data to mongo, I need to retrieve the documents, with ALL underscore prefixed fields omitted. Of course this should be done in the query rather than document manipulation after retrieval.
$ regex,$ in,$ all之类的所有运算符似乎都适用于 values .我需要建立一个基于其名称而忽略未知数量字段的投影.像这样:
All the operators like $regex, $in, $all seem to apply to values. I need to build a projection that ignores an unknown number of fields based on their name. Something like:
db.coll.find({}, {"_*": 0})
当然不行,但是可以解释这个想法.
Of course that doesn't work, but explains the idea.
我应该注意:这是必要的,因为文档可以由我们的应用程序用户编辑,因此我不知道该架构是什么样的.我确实知道我们的内部"字段以_作为前缀,并且需要通过省略编辑器来保护这些字段.
I should note: this is necessary because the documents are editable by our application users, so I have no idea what the schema might look like. I do know our "internal" fields are prefixed with an _, and those need to be protected by omission from the editor.
希望这很简单...
推荐答案
您可以使用hidden_fields
之类的单独字段.请参阅以下架构.
You can have a separate field as hidden_fields
or something. See the following schema.
{_id: 'myid1', hidden_fields: {"_foo": "bar", "_foo2": "bar2"}, key1: value1 ...}
现在在上述模式的基础上就可以了,
Now on the basis of above schema just do,
db.collection.find({ ... }, {hidden_fields: 1})
这将显示隐藏的字段.此外,您还可以在子文档中的字段上建立索引,因此也不会损失性能.
This will display hidden fields. Also you can have indexes on fields within sub documents so no loss in terms of performance as well.
这篇关于MongoDB查询-限制名称与模式匹配的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!