mongo 4.0如下版本 類型轉換

1.文檔格式

 "Values" : [ 
        {
            "key" : "姓名",
            "value" : "jenny"
        }, 
        {
            "key" : "年齡",
            "value" : "20"
        }]
2.查詢

將values字段平鋪到根。並將年齡字段值轉換成int。按姓名降序

db.getCollection('Users').aggregate([
{$addFields: {
        ValueObj: {
          $arrayToObject: {
            $map: {
              input: "$Values",
              as: "field",
        //單個條件
             // in: {$cond:[{$eq:["$$field.key","年齡"]},["$$field.key", NumberInt("$$field.value")],["$$field.key", "$$field.value"]]}
        //多個條件。3.4版本
                 in:{$switch:{branches:[{case:{$eq:["$$field.key","年齡"]},then:["$$field.key", NumberInt("$$field.value")]},
{case:{$eq:["$$field.key","年齡"]},then:["$$field.key", NumberInt("$$field.value")]}],
default:["$$field.key", "$$field.value"]}} } } } } }, {$addFields:{"ValueObj.Values":"$Values"}}, {$replaceRoot:{newRoot:"$ValueObj"}}, {$sort:{"姓名":-1}}, ]) 3.結果 "姓名" : "jenny", "年齡" : 20, "Values" : [ { "key" : "姓名", "value" : "jenny" }, { "key" : "年齡", "value" : "20" }]
相關文章
相關標籤/搜索