繁体   English   中英

如何以嵌套对象数组为条件来检索文档?

[英]How to retrieve documents with conditioning an array of nested objects?

存储在mongodb中的对象的结构如下:

obj = {_id: "55c898787c2ab821e23e4661", ingredients: [{name: "ingredient1", value: "70.2"}, {name: "ingredient2", value: "34"}, {name: "ingredient3", value: "15.2"}, ...]}

我想做的是检索所有文档,其中特定成分的值大于任意数字。

更具体地说,假设我们要检索包含名称为“ ingredient1”且其值大于50的成分的所有文档。

尝试以下操作,我无法检索到所需的结果:

var collection = db.get('docs');
var queryTest = collection.find({$where: 'this.ingredients.name == "ingredient1" && parseFloat(this.ingredients.value) > 50'}, function(e, docs) {
                                    console.log(docs);
                                });

有谁知道针对特定数组元素名称和值的正确查询是什么?

谢谢!

$where这里,您真的不需要$where的JavaScript评估,只需对$elemMatch查询使用基本查询运算符$elemMatch 虽然这里的“值”元素实际上是字符串,但这并不是真正的重点(正如我在本文结尾所解释的)。 要点是第一次就将其正确设置:

collection.find(
    {
        "ingredients": {
            "$elemMatch": {
                "name": "ingredient1",
                "value": { "$gt": 50 }
            }
         }
    },
    { "ingredients.$": 1 }
)

第二部分中的$是位置运算符 ,该位置运算符仅从查询条件中投影数组的匹配元素。

这也比JavaScript评估快得多,因为不需要编译评估代码并使用本机编码的运算符,并且可以在“名称”甚至“值”元素上使用“索引”数组以帮助过滤匹配项。

如果期望数组中有多个匹配项,则.aggregate()命令是最佳选择。 对于现代的MongoDB版本,这非常简单:

collection.aggregate([
    { "$match": {
        "ingredients": {
            "$elemMatch": {
                "name": "ingredient1",
                "value": { "$gt": 50 }
            }
         }
    }},
    { "$redact": {
        "$cond": {
            "if": { 
               "$and": [
                   { "$eq": [ { "$ifNull": [ "$name", "ingredient1" ] }, "ingredient1" ] },
                   { "$gt": [ { "$ifNull": [ "$value", 60 ] }, 50 ] }
               ]
            },
            "then": "$$DESCEND",
            "else": "$$PRUNE"
        }
    }}
])

甚至在引入$filter运算符的即将发布的版本中更简单:

collection.aggregate([
    { "$match": {
        "ingredients": {
            "$elemMatch": {
                "name": "ingredient1",
                "value": { "$gt": 50 }
            }
         }
    }},
    { "$project": {
        "ingredients": {
            "$filter": {
                "input": "$ingredients",
                "as": "ingredient",
                "cond": {
                    "$and": [
                        { "$eq": [ "$$ingredient.name", "ingredient1" ] },
                        { "$gt": [ "$$ingredient.value", 50 ] }
                    ]
                }
            }
        }
    }}
])

在两种情况下,您都有效地“过滤”了在初始文档匹配后不符合条件的数组元素。


另外,由于您的“值”实际上实际上是“字符串”,因此您应该将其更改为数字。 这是一个基本过程:

var bulk = collection.initializeOrderedBulkOp(),
    count = 0;

collection.find().forEach(function(doc) {
    doc.ingredients.forEach(function(ingredient,idx) {
        var update = { "$set": {} };
        update["$set"]["ingredients." + idx + ".value"] = parseFloat(ingredients.value);
        bulk.find({ "_id": doc._id }).updateOne(update);
        count++;

        if ( count % 1000 != 0 ) {
            bulk.execute();
            bulk = collection.initializeOrderedBulkOp();
        }
    })
]);

if ( count % 1000 != 0 )
    bulk.execute();

这样就可以修复数据,以便此处的查询表单起作用。

这比使用JavaScript $where进行处理要好得多,JavaScript $where需要评估集合中的每个文档,而没有使用要过滤的索引的好处。 正确的形式是:

collection.find(function() {
    return this.ingredients.some(function(ingredient) { 
        return ( 
           ( ingredient.name === "ingredient1" ) && 
           ( parseFloat(ingredient.value) > 50 ) 
        );
    });
})

而且,这也无法像其他形式一样“投影”结果中的匹配值。

尝试使用$ elemMatch:

var queryTest = collection.find(
   { ingredients: { $elemMatch: { name: "ingredient1", value: { $gte: 50 } } } }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM