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

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

问题描述

我浏览了MongoDB文档并用谷歌搜索了这个问题,但找不到真正合适的答案.所以,这就是我要寻找的. 假设我有一个包含这样的元素的集合:

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: <your string> } }

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(<collection_name>).find({ $text: { $search: <your string> } });

有关控制搜索的各种方式的更多信息,请参见此处的mongodb文档,以了解文本搜索

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

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

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