如果这是您的搜索案例,那么无论您如何看待它,您都需要对 $where 子句进行 JavaScript 评估来解析您当前的结构。在 shell 示例中(因为无论如何您都需要使用 JavaScript 表达式):
db.collection.find(function() {
var root = this.test.item_obj;
return Object.keys(root).some(function(key) {
return root[key] == "a";
});
})
或者对于像这样的mongoid:
func = <<-eof
var root = this.test.item_obj;
return Object.keys(root).some(function(key) {
return root[key] == "a";
});
eof
Model.for_js(func)
但是,如果您只是更改结构以将“items_objects”定义为数组,如下所示:
{
"_id": 1,
"test": {
"item_objects": [
{ "name": "item1", "data": ["a","b"] },
{ "name": "item2", "data": ["c"] },
{ "name": "item3", "data": ["a","d"] }
}
}
}
然后在这里询问你想要什么就像:
db.collection.find({
"test.item_objects.data": "a"
})
或者对于mongoid:
Model.where( "test.item_objects.data" => "a" )
虽然嵌套数组并不是一个好主意,所以也许可以接受:
{
"_id": 1,
"test": {
"item_objects": [
{ "name": "item1", "data": "a" },
{ "name": "item1", "data": "b" },
{ "name": "item2", "data": "c" },
{ "name": "item3", "data": "a" },
{ "name": "item3", "data": "d" }
}
}
}
这基本上是一样的,但更啰嗦。但最终在原子更新中更容易处理。当然,在文档中查找值的查询是完全相同的。