Mongo 在数组对象中查询
Mongo query in Object of arrays
文档示例
{
"_id": 1,
"test": {
"item_obj": {
"item1": ["a", "b"],
"item2": ["c"],
"item3": ["a", "d"]
}
}
}
我想fetch documents where "a" exists in test.item_obj
。 "a" 可能存在于任何数组中。而且我们不知道 item_obj 中存在的键(不知道 item1、item2 或 item3 是否存在)。
需要rails-mongo查询。
如果这是您的搜索案例,那么无论您如何看待它,您都需要 JavaScript 对 $where
子句的评估来解析您当前的结构。在 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" }
}
}
}
这基本上是一回事,只是比较啰嗦。但最终在原子更新中更容易处理。当然,在文档中查找值的查询也完全相同。
文档示例
{
"_id": 1,
"test": {
"item_obj": {
"item1": ["a", "b"],
"item2": ["c"],
"item3": ["a", "d"]
}
}
}
我想fetch documents where "a" exists in test.item_obj
。 "a" 可能存在于任何数组中。而且我们不知道 item_obj 中存在的键(不知道 item1、item2 或 item3 是否存在)。
需要rails-mongo查询。
如果这是您的搜索案例,那么无论您如何看待它,您都需要 JavaScript 对 $where
子句的评估来解析您当前的结构。在 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" }
}
}
}
这基本上是一回事,只是比较啰嗦。但最终在原子更新中更容易处理。当然,在文档中查找值的查询也完全相同。