为什么我需要在$ switch默认语句中指定它为可选内容?

时间:2018-10-17 10:20:38

标签: mongodb aggregation-framework

我想更新条件文件。我尝试了$ cond,但是它需要一个用于错误大小写的表达式。而且我也不想更新任何错误的内容。以下是文档示例:

{
    "_id" : ObjectId("5bc29e0d0fc2c40a9d628afe"),
    "BasicInfo" : {
        "RepNo" : "AE179",
        "CompanyName" : "First Bancshares Inc",
        "IRSNo" : "640862173",
        "CIKNo" : "0000947559",
        "Name" : "Ordinary Shares",
        "Ticker" : "FBMS",
        "CUSIP" : "318916103",
        "ISIN" : "US3189161033",
        "RIC" : "FBMS.O",
        "SEDOL" : "2184300",
        "DisplayRIC" : "FBMS.OQ",
        "InstrumentPI" : "10552665",
        "QuotePI" : "26300255",
        "Exchange" : "NASDAQ"
    },
    "Annual" : {
        "Date" : ISODate("2017-12-31T00:00:00.000Z"),
        "INC" : {
            "SIIB" : {
                "Description" : "Interest Income, Bank",
                "Value" : 66.06941
            },
            "STIE" : {
                "Description" : "Total Interest Expense",
                "Value" : 6.90925
            },
            "ENII" : {
                "Description" : "Net Interest Income",
                "Value" : 59.16016

然后,由于文档说默认语句是可选的,所以我尝试使用$ switch。

我已经编写了以下代码:

db.getCollection('FinancialStatement').aggregate([
{"$unwind":"$Annual"},
{"$addFields":{"Annual.Price":
    {"$switch":{
        branches:[
        {
            case: {
                "$and":[
                {"$eq":["$_id", ObjectId("5bc29e0d0fc2c40a9d628afe")]}, 
                {"$eq":["$Annual.Date", ISODate("2017-12-31 00:00:00.000Z")]}
                ]
        },
        then: 1000}
    ],
        default: -2000
        }
        }
        }
}
]
)

如果满足objectID和日期要求,则基本上会添加一个名为Annual.price的新字段。但是,如果我忽略了默认语句,程序将返回错误消息:

Assert: command failed: {
    "ok" : 0,
    "errmsg" : "$switch could not find a matching branch for an input, and no default was specified.",
    "code" : 40066,
    "codeName" : "Location40066"
}

1 个答案:

答案 0 :(得分:1)

有关使用default的文档

  

可选。如果没有分支大小写表达式求和的路径   是的。

     

尽管是可选的,但如果未指定default且没有分支大小写   计算结果为true,$ switch返回错误。

在3.6中使用$$REMOVE

类似

使用$cond

{"$addFields":{
  "Annual.Price":{
    "$cond":[
        {
          "$and":[
            {"$eq":["$_id",ObjectId("5bc29e0d0fc2c40a9d628afe")]},
            {"$eq":["$Annual.Date",ISODate("2017-12-31 00:00:00.000Z")]}
          ]
        },
      1000,
      "$$REMOVE"
    ]
  }
}}

使用$switch

{"$addFields":{
  "Annual.Price":{
    "$switch":{
      "branches":[
        {
          "case":{
            "$and":[
              {"$eq":["$_id",ObjectId("5bc29e0d0fc2c40a9d628afe")]},
              {"$eq":["$Annual.Date",ISODate("2017-12-31 00:00:00.000Z")]}
            ]
          },
          "then":1000
        }
      ],
      "default":"$$REMOVE"
    }
  }
}}