mongodb - 蒙戈 : querying for values nested in child arrays where keys are variable

标签 mongodb

我正在尝试构建一个 Mongo 查询,在其中我可以根据子数组内的值选择文档,其中嵌入数组的键将随文档的不同而变化。

在下面的示例中,我们有三个文档数组。提取每种酒的名称很简单。当我想要选择品尝结果大于 20 的 Wine 时,问题就出现了。问题是,当我运行查询时,我不知道航类的名称;它可以是任何东西。

因此,我不能只检查嵌入数组的值。

我考虑过类似的事情

$ary_query = array('tasting_results.*' => '$gt: 20');

但显然通配符在 Mongo 中不起作用(至少不是那样)。有什么想法吗?

这是示例数组:

ary_wines = array(
"name" => "Ripple",
"year" => "2013",
"style" => "cabernet", 
"size" => "750ml",
"tasting_results" => array (
    "flight_42" => 12,
    "flight_2" => 18,
    "flight_33" => 7 
    )
)

ary_wines = array(
"name" => "Riunite",
"year" => "2012",
"style" => "White Zinfandel", 
"size" => "1.5L",
"tasting_score" => array (
    "flight_6" => 14,
    "flight_54" => 21,
    "flight_98" => 3 
    )
)

ary_wines = array(
"name" => "Maneschewitz",
"year" => "2012",
"style" => "Grape Juice", 
"size" => "500ml",
"tasting_score" => array (
    "flight_7" => 12,
    "flight_41" => 26,
    "flight_9" => 3 
    )
)

最佳答案

好吧,从技术上讲,您可以使用 $where 子句执行表扫描样式查询:

db.wines.find({$where: function() {
    var keys = Object.keys(this.tasting_score);
    keys.forEach(function(key) {
        if(this.tasting_score[key] > 20) { return true; }
    });
    return false;
});

但是,我恳求您,这是一个可怕的想法,最好将数据以可索引的方式放入数据库,这样您就可以使用标准查询方法。具体如何执行此操作取决于您的应用程序将如何操作数据,但至少您可以在插入时进行预处理,并在对象中添加一个 maxTastingScore 参数来查询是否满足此条件是唯一不适合您的数据结构的查询。

关于mongodb - 蒙戈 : querying for values nested in child arrays where keys are variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9899740/

相关文章:

MongoDB Pymongo Ubuntu - 时间问题

javascript - 每第二次运行都会抛出 : MongoError: Topology was destroyed

ios - Node.JS RESTful API 的最佳身份验证方法

node.js - 如何更改 MongoDB 和 mongoose 中的日期格式

node.js - Mongoose 自定义验证失败

mongodb - 无法使用 Node.js Express MongoDB Mongoose CoffeeScript 进行 POST

mongodb - 从 bson 结构转换 protoc 生成的结构的最佳方法是什么?

spring - MongoDB GridFS 身份验证不起作用

arrays - MongoDB 更新(将项目列表插入数组)

ruby-on-rails - 如何在时间戳中转换字符串(时间或日期时间)并保存在mongodb中