首页 > 解决方案 > 聚合MongoDB 3.4

问题描述

我有一个这样的文件集。我想更改子文档中的值

{ "cities" :[
        {
            "city" : "London", 
            "country" : "United Kingdom"
        }, 
        {
            "city" : "New York", 
            "country" : "United States"
        }
        {
            "city" : "San Francisco", 
            "country" : "United States"
        }]
}

If city is San Franciscothen Sf
If city is New yorkthen NY
Elsenull

我用过$switch但不起作用。我正在使用 MongoDB v3.4

标签: mongodbaggregation-framework

解决方案


试试这个:

db.collection.aggregate([
  {
    $project: {
      cities: {
        $map: {
          input: "$cities",
          in: {
            country: "$$this.country",
            city: {
              $switch: {
                branches: [
                  {
                    case: {
                      $eq: [ "$$this.city","San Francisco"]
                    },
                    then: "Sf"
                  },
                  {
                    case: {
                      $eq: [ "$$this.city", "New York" ]
                    },
                    then: "NY"
                  }
                ],
                default: null
              }
            }
          }
        }
      }
    }
  }
  //Uncomment this stage if aggregation result meets your requirements
  //,{$out: "collection"}
])

Mongo游乐场


推荐阅读