繁体   English   中英

使用聚合在嵌套数组中选择文档的字段

[英]Select a field of a document in nested array using aggregation

我有以下文件:

{
    "options": [
        {
            "cost": 5,
            "value": {
                "en": "Socket, where I can plug in my own cable",
                "fr": "Prise, où je peux brancher mon propre câble"
            }
        },
        {
            "cost" 15,
            "value": {
                "en": "Fixed cable",
                "fr": "Câble fixe"
            }          
        }
    ]
}

我想将 en 的值作为值,如下所示:

{
    "options": [
        {
            "cost": 5,
            "value": "Socket, where I can plug in my own cable"
        },
        {
            "cost" 15,
            "value": "Fixed cable"       
        }
    ]
}

我已经尝试过使用$addFields和作为字段来访问$options.value.en或嵌套。 我也试过$map但没有结果。

我不想$unwind选项并在$addFields之后将它们$addFields

您可以使用以下聚合

db.collection.aggregate([
  { "$addFields": {
    "options": {
      "$map": {
        "input": "$options",
        "in": {
          "cost": "$$this.cost",
          "value": "$$this.value.en"
        }
      }
    }
  }}
])

尝试这个:

db.collection.aggregate([
  {
    $unwind: {
      path: "$options"
    }
  },
  {
    $project: {
      "options.cost": 1,
      "options.value": "$options.value.en"
    }
  },
  {
    $group: {
      _id: 0,
      options: {
        $push: "$options"
      }
    }
  }
])

暂无
暂无

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

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