Searching for value of any field in MongoDB without explicitly naming it

Max L. picture Max L. · Jul 22, 2011 · Viewed 70.5k times · Source

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.

In my thinking something like this

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

would give me the example element.

Thank you for your help.

Answer

dave adelson picture dave adelson · Mar 7, 2016

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

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

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

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

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

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

var cursor = db.collection(<collection_name>).find({ $text: { $search: <your string> } });

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