在 MongoDB 中搜索任何字段的值而不显式命名它

我查看了 MongoDB 文档并在谷歌上搜索了这个问题,但是没有找到合适的答案。这就是我要找的。 假设我有一个包含如下元素的集合:

{
"foo" : "bar",
"test" : "test",
"key" : "value",
}

我想要实现的是通过在所有(可能除了有限多个; ——)字段中搜索来找到一个元素。换句话说: 给定一个查询,我不知道该查询应该在哪个字段中找到。

在我看来,就像这样

db.things.find({_ANY_ : "bar"})

会给我示例元素。

谢谢你的帮助。

94522 次浏览

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"})

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

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

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

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]

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)