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, 开发者_StackOverflowhere 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.
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
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;
}});
This is not possible without individually inspecting documents app-side or through server-side code execution. Consider changing your schema to :
{params:[{field:"foo", value:"bar"}, {field:"test", value:"test"}, {field:"key", value:"value"}]}
This obviously has some downsides (performance and poluted schema mostly) but will allow what you need through :
db.things.find({'params.value':"bar"})
Sadly, none of the previous answers address the fact that mongo can contain nested values in arrays or nested objects.
THIS IS THE CORRECT QUERY:
{$where: function() {
var deepIterate = function (obj, value) {
for (var field in obj) {
if (obj[field] == value){
return true;
}
var found = false;
if ( typeof obj[field] === 'object') {
found = deepIterate(obj[field], value)
if (found) { return true; }
}
}
return false;
};
return deepIterate(this, "573c79aef4ef4b9a9523028f")
}}
Since calling typeof on array or nested object will return 'object' this means that the query will iterate on all nested elements and will iterate through all of then until the key with value will be found.
You can check previous answers with a nested value and the results will be far from desired.
Stringifying the whole object is far less performant since it has to iterate through all memory sectors one by one trying to match them. And creates a copy of the object as a string in ram memory (both inefficient since query uses more ram and slow since function context already has a loaded object)
Using $where is the same as doing a full table scan and cannot use the indexes. I also could not get it working, however I did find this worked (it also does the equivalent of a full table scan) :
db.collection.find().forEach(function(doc){
for (var key in doc) {
if ( /needle/.test(doc[key]) )
printjson(doc);
}
});
where /needle/
is a regular expression to find in the value of doc[key]
You can do it with a recursive function:
var recursiveSearch = function(query) {
db.test_insert.find().forEach(function(items) {
var i = 0;
var recursiveFunc = function(itemsArray, itemKey) {
var itemValue = itemsArray[itemKey];
if(itemValue === query) {
printjson(items);
}
if(typeof itemValue === "object") {
Object.keys(itemValue).forEach(function(itemValueKey) {
recursiveFunc(itemValue, itemValueKey);
});
}
};
Object.keys(items).forEach(function(item){
recursiveFunc(items, item);
});
});
};
recursiveSearch('your string');
To do text search, you have to create text indexes for your collection. For more information, look at mongo documentation :indexes text
A quick-and-dirty whole-database search for MongoDB is to export the database to JSON and to grep
through the export:
database="your-database-name" outdir="outdir-name" \
mongo --quiet $database --eval "db.getCollectionNames().join('\n')" | \
grep -v system.indexes | \
xargs -L 1 -I {} mongoexport -d $database -c {} --out $outdir/{}.json
grep "search-term" $outdir
Of course then your search term will match on both key names and values, but sometimes that is even handy (e.g. developer trying to find a field after document structure changes in a large document).
This solution will be very inefficient for massive databases, but it's handy during development when only test data is present.
The source, with more details and explanations, for the MongoDB export to JSON is Tom Boutell's answer for "How to export all collections in MongoDB?".
精彩评论