5

I'm asking this question after studying MongoDB text search and keyword indexes. I also found a similar question, but adding an array to each document containing all the field values seems like a kludgy solution. Thus this question.

We need to write a query that will return documents where any field matches a search string.

Our first thought was to write a query along these lines:

db.collection.find( { field_one: /search string/i, 
                      field_two: /search string/i,
                      field_three: /search string/i } );

Our challenge is that the fields will vary between documents, so we can't hard-code the field names in the query.

Is something like the following pseudocode possible with MongoDB?

db.collection.find( { [any field]: /search string/i } );
Community
  • 1
  • 1
Jedidiah Hurt
  • 812
  • 9
  • 20
  • no, it's not possible to search for fields without knowing their name. this is typical of a database - it looks like you need a search engine rather than a database. – Asya Kamsky Nov 13 '13 at 19:30
  • Hi Jedidiah - Did you find the solution? I also got the same requirement where I want to search string in whole documents of collection but where I am not aware field name (may always change) going to be.. Please help... Thanks, Deepali –  Oct 11 '15 at 21:17
  • 1
    @user4567570 it was so long ago now, I can't remember the exact details. But I'm pretty sure we went with `.find({ $where: function () {...} })` as the collections we were querying were not very large. See here for further explanation: http://stackoverflow.com/a/19802670/825421 – Jedidiah Hurt Oct 20 '15 at 03:17

1 Answers1

5

Maybe it's not exactly what you are looking for, but if you are considering a schema restructure that allows such a query, this post appears to be interesting:

MongoDB Query Help - query on values of any key in a sub-object

Community
  • 1
  • 1
rdonatoiop
  • 1,185
  • 1
  • 14
  • 28