简体   繁体   English

使用正则表达式在MongoDB中搜索任何值?

[英]Search any value in MongoDB using regular expressions?

I'm very new to MongoDB and regex so please bear with me. 我对MongoDB和regex非常陌生,所以请多多包涵。 The MongoDB documentation has an example for searching with regular expressions: MongoDB文档提供了一个使用正则表达式进行搜索的示例:

http://docs.mongodb.org/manual/reference/operators/#_S_regex http://docs.mongodb.org/manual/reference/operators/#_S_regex

However, it only shows how to search the values of predetermined keys. 但是,它仅显示了如何搜索预定键的值。 I'm unsure how to write a query to search all values in a collection, if anyone can point it out that would be great. 我不确定如何编写查询来搜索集合中的所有值,如果有人可以指出的话,那会很棒。

If you didn't care about size of DB (or performance), you could potentially use a mapReduce function to de-normalize the data into a structure which is more easily searched. 如果您不关心数据库的大小(或性能),则可以使用mapReduce函数将数据反规范化为更易于搜索的结构。 But, this will significantly increase the size of the DB as you'll duplicate all data for the collection. 但是,这将大大增加数据库的大小,因为您将复制该集合的所有数据。

Pseudo-code: 伪代码:

// recursive
// building a full property path
for(var key in obj) {
    emit(this._id, { orig: obj[key], src: path + "." + key });
    // recursive call emitChildren(path, key)
}

Depending on the complexity of the data, it could be reasonable. 根据数据的复杂性,这可能是合理的。

Or, you might be able to use $where to do a regex on each key/value of all documents (as you can execute arbitrary JavaScript when using $where). 或者,您可能可以使用$ where对所有文档的每个键/值进行正则表达式(因为使用$ where时可以执行任意JavaScript)。

No option is going to perform well (even a built in option) nor play to the strengths of mongoDB if you're running a regular expression on every value in every document in a collection. 如果您要对集合中每个文档中的每个值运行正则表达式,那么任何选项都不会表现良好(甚至是内置选项),也不会发挥mongoDB的优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM