Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 680
Max L. Avatar asked Jul 22 '11 13:07

Max L.


People also ask

How do I search for text in a field in MongoDB?

In MongoDB, we can perform text search using text index and $text operator. Text index: MongoDB proved text indexes that are used to find the specified text from the string content. Text indexes should be either a string or an array of string elements.


2 Answers

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

like image 69
dave adelson Avatar answered Oct 11 '22 10:10

dave adelson


This answer to a similar question has your solution, which I'll repeat here for completeness. You can use the $where operator to run arbitrary JavaScript on the MongoDB server(s), with the caveat that this will be much slower than almost any other kind of query. For your example, it would be:

db.things.find({$where: function() {     for (var key in this) {         if (this[key] === "bar") {             return true;         }     }     return false; }}); 
like image 45
Tom Panning Avatar answered Oct 11 '22 10:10

Tom Panning