1. 程式人生 > >mongodb update多層巢狀陣列解決辦法

mongodb update多層巢狀陣列解決辦法

version: 3.4.3

{ "_id" : 1
  "user_id": 1,
  "message" : "Yes"
  "translations" : [
    { 
      "destination" : "fr",
      "text": "Oui"
    },
    { 
      "destination" : "bf",
      "text": "uid"
    },
  ]
}

如果是一層陣列,可以用如下語句更新數組裡指定key的value

db.getCollection('message').update({
    '_id': 1
, 'translations.destination': 'fr' }, { '$set': { "translations.$.text": "asd" } }

如果再加一層巢狀

{ "_id" : 1
  "user_id": 1,
  "message" : "Yes"
  "translations" : [
    { 
      "destination" : "fr",
      "text": "Oui",
      "rating" : [
        { "user_id" : 1,
          "rating
" : 1 }, { "user_id" : 2, "rating" : 1 } ]
} ]
}

使用這個更新語句就會報錯了

db.getCollection('message').update({
    '_id': 1,
    'translations.destination': 'fr',
    'translations.rating.user_id':'1'
},
{
    '$set': {
        "translations.$.rating.$.rating": 5
} }

目前mongodb不支援多個$佔位符,推薦的方法的修改資料結構,把資料格式改成這樣,把陣列元素改成key-value形式

{ "_id" : 1
  "user_id": 1,
  "message" : "Yes"
  "translations" : {
    "fr": { 
      "destination" : "fr",
      "text": "Oui",
      "rating" : [
        { "user_id" : 1,
          "rating" : 1
        },
        { "user_id" : 2,
          "rating" : 1
        }
      }
    },
    "en": {...}
  ]
}

執行如下更新語句

db.getCollection('message').update({
    '_id': 1,
    'translations.destination': 'fr',
    'translations.rating.user_id':'1'
},
{
    '$set': {
       translations.fr.rating.$.rating”: 5
    }
}

ps:只能使用一個$佔位符的問題在社群裡已經提了很久了,一直沒有得到解決,希望下個版本可以解決