在 MongoDB 中搜索任何字段的值而不显式命名它 [英] Searching for value of any field in MongoDB without explicitly naming it

查看:12
本文介绍了在 MongoDB 中搜索任何字段的值而不显式命名它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了 MongoDB 文档并在 google 上搜索了这个问题,但找不到合适的答案.所以,这就是我要找的.假设我有一个包含以下元素的集合:

I looked through the MongoDB documentation and googled this question but couldn't really find a suitable answer. So, here is what I'm looking for. Assume I have a collection with elements like this:

{
   "foo" : "bar",
   "test" : "test",
   "key" : "value",
}

我想要实现的是通过在所有(可能除了有限多个 ;-) )字段中搜索来找到一个元素.换句话说:给定一个查询,我不知道应该在哪个字段中找到该查询.

What I'd like to achieve is find an element by searching in all (maybe except for finitely many ;-) ) fields. In other words: Given a query, I do NOT know in which field the query should be found.

我的想法是这样的

db.things.find({_ANY_ : "bar"}) 

会给我示例元素.

感谢您的帮助.

推荐答案

要对所有字段进行文本搜索,首先必须在所有字段上创建文本索引.

to do a text search on all fields, you first must create a text index on all fields.

正如 mongodb 文档 所指出的,为了允许对包含字符串内容的所有字段进行文本搜索,使用通配符说明符 ($**) 对包含字符串内容的所有字段进行索引."

as the mongodb documentation indicates, "To allow for text search on all fields with string content, use the wildcard specifier ($**) to index all fields that contain string content."

如果您在 mongo shell 中工作(通过调用 'mongo' 从命令行执行),那么您可以使用此命令执行此操作,其中 'collection' 是您想要的数据库中集合的名称使用.

if you are working inside the mongo shell (which you execute from the command line by calling 'mongo'), then you can do it with this command, where 'collection' is the name of the collection in the db you want to use.

db.collection.createIndex({ "$**": "text" },{ name: "TextIndex" })

第二个对象,即{name:"TextIndex"},是可选的...实际上您不需要为索引命名,因为只能有一个文本索引每个集合(一次……如果需要,您可以删除索引并创建新索引).

the second object, i.e. {name:"TextIndex"}, is optional...you don't actually need to give the index a name, since there can only be a single text index per collection (at a time...you can drop indexes and create new ones if you want).

在所有字段上创建文本索引后,您可以使用以下查询对象进行简单的文本搜索:{ $text : { $search: <你的字符串>} }

once you have created a text index on all fields, you can do a simple text search with the following query object: { $text : { $search: <your string> } }

因此,如果您正在编写 javascript 函数,您可能会执行以下操作:

so, if you are writing a javascript function you might do something like:

var cursor = db.collection().find({ $text: { $search: } });

有关控制搜索的各种方法的更多信息,请参阅有关文本搜索的 mongodb 文档此处

for more info on the various ways to control the search, see the mongodb documentation on text searching here

这篇关于在 MongoDB 中搜索任何字段的值而不显式命名它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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