为什么 MongoDB 不支持查询使用哈希存储的嵌入式文档的属性?
例如,假设您有一个名为“invoices”的集合,它是这样创建的:
db.invoices.insert(
[
{
productsBySku: {
12432: {
price: 49.99,
qty_in_stock: 4
},
54352: {
price: 29.99,
qty_in_stock: 5
}
}
},
{
productsBySku: {
42432: {
price: 69.99,
qty_in_stock: 0
},
53352: {
price: 19.99,
qty_in_stock: 5
}
}
}
]
);
使用这种结构,使用 $elemMatch、点语法或位置运算符 ($) 的 MongoDB 查询无法访问每个 productsBySku 成员的任何属性。
例如,您不能执行以下任何操作:
db.invoices.find({"productsBySku.qty_in_stock":0});
db.invoices.find({"productsBySku.$.qty_in_stock":0});
db.invoices.find({"productsBySku.qty_in_stock":{$elemMatch:{$eq:0}}});
db.invoices.find({"productsBySku.$.qty_in_stock":{$elemMatch:{$eq:0}}});
因此,要查找缺货产品,您必须使用 $where 查询,例如:
db.invoices.find({
$where: function () {
for (var i in this.productsBySku)
if (!this.productsBySku[i].qty_in_stock)
return this;
}
});
在技术层面上......为什么他们设计 MongoDB 时对查询有非常严格的限制?对于这个看似重大的缺陷,肯定有某种技术原因。这是否无法将对象列表作为数组处理,忽略键,只是 JavaScript 作为一种语言的限制?或者这是 MongoDB 内部某些架构决策的结果?
只是好奇。