jezzarax
jezzarax

Reputation: 413

Find documents that contain search string in any field

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.

Upvotes: 1

Views: 1042

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

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'});

Upvotes: 1

Related Questions