MongoDB elemmatch数组中的多个元素

标签 mongodb mongodb-query aggregation-framework

我有一个像

这样的 mongodb 文档
    {
        "_id" : ObjectId("54e66b2da7b5f3a92e09dc6c"),
        "SomeMetric" : [ 
            {
                //some object
            }
            {
                //some object
            } 
         ],
        "FilterMetric" : [ 
            {
                "min" : "0.00",
                "max" : "16.83",
                "avg" : "0.00",
                "class" : "s1"
            }, 
            {
                "min" : "0.00",
                "max" : "16.83",
                "avg" : "0.00",
                "class" : "s2"
            }, 
            {
                "min" : "0.00",
                "max" : "16.83",
                "avg" : "0.00",
                "class" : "s1"
            }, 
            {
                "min" : "0.00",
                "max" : "16.83",
                "avg" : "0.00",
                "class" : "s2"
            } 
        ]
    }

通常它包含许多这样的嵌套数组。我想单独投影一个指标,只有具有我的搜索条件的数组。 我有疑问

db.sample.find(
{"filtermetric.class" : "s2"},{"filtermetric" : { $elemMatch : {class: "s2"}}}
)

这只会给我数组中的第一个对象。不返回具有类 : s2 的第二个对象。

如果我尝试

    db.sample.find(
   {"filtermetric" : { $elemMatch : {class: "s2"}}}
    )

它给了我数组中的所有 4 个对象。

在这种情况下如何获取所有符合条件的对象?

最佳答案

您不能以任何形式的基本 .find() 查询返回与您的条件匹配的数组的多个元素。要匹配多个元素,您需要使用 .aggregate()方法来代替。

这里的主要区别在于“查询”完全按照它的意图执行并匹配满足您条件的“文档”。您可以尝试使用positional $投影参数中的运算符,但规则是它只会匹配与查询条件匹配的“第一个”数组元素。

为了对多个数组元素进行“过滤”,请执行以下操作:

db.sample.aggregate([
    // Filter possible documents
    { "$match": { "filtermetric.class": "s2" } },

    // Unwind the array to denormalize
    { "$unwind": "$filtermetric" },

    // Match specific array elements
    { "$match": { "filtermetric.class": "s2" } },

    // Group back to array form
    { "$group": {
        "_id": "$_id",
        "filtermetric": { "$push": "$filtermetric" }
    }}
])

在 2.6 或更高版本的现代 MongoDB 版本中,您可以使用 $redact 执行此操作:

db.sample.aggregate([
    // Filter possible documents
    { "$match": { "filtermetric.class": "s2" } },

    // Redact the entries that do not match
    { "$redact": {
        "$cond": [
            { "$eq": [ { "$ifNull": [ "$class", "s2" ] }, "s2" ] },
            "$$DESCEND",
            "$$PRUNE"
        ]
    }}
])

这可能是您最有效的选择,但它是递归的,因此请首先考虑您的文档结构,因为在任何级别的任何其他条件下都不能存在相同的命名字段。

这种技术可能更安全,但只有在数组中的结果“真正独特”时才有用$map。和 $setDifference :

db.sample.aggregate([
    { "$project": {
        "filtermetric": { "$setDifference": [
            { "$map": [
                "input": "$filtermetric",
                "as": "el",
                "in": {"$cond": [
                    { "$eq": [ "$$el.class", "s2" ] },
                    "$$el",
                    false
                ]}
            ]},
            [false]
        ]}
    }}
])

同时注意到 $group$project需要指定您打算在该阶段的结果文档中返回的所有字段。

最后一点是 $elemMatch当您只查询数组中单个键的值时,不需要。 "Dot notation"在仅访问数组的单个键时是首选和推荐的。 $elemMatch 仅当数组“元素”内文档中的“多个”键需要匹配查询条件时才需要。

关于MongoDB elemmatch数组中的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026662/

相关文章:

python - 使用matplotlib的Mongodb数据统计可视化

java - 如何在 Spring Data MongoDB 中投影 $strLenCP

java - 具有线性分布的 Group 和 Sum MongoDb 聚合框架

mongodb - 如何返回文档的位置,相对于 MongoDB 中的集合(可扩展)

node.js - MongoDB 搜索用户 : filter based on name with regex

使用 Haskell 驱动程序进行 MongoDB 全文搜索

mongodb - Golang mgo 返回带有聚合 $group 的值

mongodb - 按数组元素比较查找

node.js - 使用 RoboMongo 生成新的 ObjectId

javascript - findOneAndUpdate Mongoose 函数中的字符串文字问题