1

I'm trying to find the best way to make MongoDb look for a specific value in all document's fields. For example if I have two documents:

{
    field1: "value1"
    field2: "value2"
}

and

{
    field3: "value3"
    field4: "value1"
}

and the query string is "value1" both documents will be returned.

If there's no way to do it in MongoDb, what's the best strategy to implement it on database or code level? I tried to make a getter in C# that iterates over all mapped entity's properties and returns an array and to store this array in the database but IMO it is inefficient and ugly solution.

jezzarax
  • 417
  • 2
  • 10
  • [Here's a workable answer](http://stackoverflow.com/a/19802670/825421) from a duplicate question (though the solution may be too slow for you ). – Jedidiah Hurt Nov 13 '13 at 18:27

1 Answers1

1

There's not a way to directly do that in MongoDB.

Having an unbounded set of field names may be a sign your schema needs to be re-worked. Have you considered making your dynamic field names be values of an embedded object instead? As in:

fields: [{name: "field1", value: "value1"}, {name: "field2", value: "value2"}]

Then your query would look like:

db.coll.find({'fields.value': 'value1'});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • The schema was fine until the customer suddenly asked me to make all-field-wide search, so now I need to find a way to implement it. I have several c# classes mapped to mongodb collections and reworking it to arrays of key-value pairs seems to be too hardcore :-) I tried to make more lightweight solution I described in the question but I still hope to find easier way – jezzarax May 03 '13 at 21:15