【问题标题】:Extract a value from an object in array matching a condition从匹配条件的数组中的对象中提取值
【发布时间】:2019-06-08 12:10:37
【问题描述】:

我需要帮助在 mongodb 中创建聚合管道。

我使用的mongodb版本是4。

存储在数据库中的文档如下所示:

 [{
    _id : "xxxxxx",
    names : [
        { "lang" : "EN", value : "foo" },
        { "lang" : "IT", value : "bar" },
        { "lang" : "NOLANG", value : "baz" }
    ],
    some : "value"
},{
    _id : "yyyyyy",
    names : [
        { "lang" : "FR", value : "quux" },
        { "lang" : "IT", value : "quuux" },
        { "lang" : "NOLANG", value : "quuuux" }
    ],
    some : "value"
}]

我需要添加一个包含某种语言值的聚合字段(对于本例,我将采用“EN”),如果没有找到具有请求语言的元素,我需要获取“NOLANG”对象值.

所以,聚合的结果一定是这样的:

 [{
    _id : "xxxxxx",
    name : "foo",
    some : "value"
},{
    _id : "yyyyyy",
    name : "quuuux",
    some : "value"
}]

这是我写的管道:

[
    {
        $project : {
            names : 0,
            name: {
                $filter: {
                    input: '$names',
                    as: 'name',
                    cond: {
                        $switch: {
                            $branches: [
                                {
                                    case : {
                                        $eq : ["$$name.lang", "EN"]
                                    },
                                    then : "$$name.value"
                                } ,{
                                    case : {
                                        $eq : ["$$name.lang", "NOLANG"]
                                    },
                                    then : "$$name.value"
                                }
                            ],
                            default : ''
                        }
                    }
                }
            }
        }
    }
]

它给了我错误:预期为“[”或 AggregationStage 但找到“{”。

我做错了什么?有人可以帮帮我吗?

谢谢

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

    db.collection.aggregate([
      { "$project": {
        "some": 1,
        "name": {
          "$arrayElemAt": [
            "$names.value",
            {
              "$cond": [
                {
                  "$ne": [
                    { "$indexOfArray": ["$names.lang", "EN"] },
                    -1
                  ]
                },
                { "$indexOfArray": ["$names.lang", "EN"] },
                { "$indexOfArray": ["$names.lang", "NOLANG"] }
              ]
            }
          ]
        }
      }}
    ])
    

    Output

    [
      {
        "_id": "xxxxxx",
        "name": "baz",
        "some": "value"
      },
      {
        "_id": "yyyyyy",
        "name": "quuuux",
        "some": "value"
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2013-04-06
      相关资源
      最近更新 更多