How to find value in a mongoDB collection, independently from the field name?
Assuming a collection like this:
People
{
"name": "John Doe",
"email": "John Doe <john@doe.com>",
"stuff": "foo"
"morestuff": "bar"
},
{
"name": "Homer Simpson",
"email": "Homer Simpson <homer@simpson.tv>",
"stuff"开发者_开发问答: "bar"
"morestuff": "foo"
},
{
"name": "Bart Simpson",
"email": "Bart Simpson <bart@simpson.tv>",
"stuff" : "foo"
"morestuff": "foo"
"evenmore": ["bar", "foo", "baz"]
}
What might be the best way to find all occurrences of the string 'foo' (exactly, no substring), where ever it might occur? What I'd like to accomplish is to update all occurrences of the string 'foo' to some other string, or delete it from a document in the collection.
I know this might look like a bad database design, I just want to make clear what I'd like to do :)
There is no query that will do that.
For the general case, you have to iterate over all documents, and look at all properties.
If you can limit the possible property keys, you can construct a query like
name = 'foo' or email = 'foo' or stuff ='foo'
or morestuff = 'foo' or evenmore = 'foo'
If the latter is possible, you can also split it into separate queries for every field, which makes sense because you can then also turn them into atomic update queries to change the value to the new one.
精彩评论