简体   繁体   English

如何在 mongo db 的数组列表中添加字段

[英]How to add fields in array list in mongo db

{
    "_id" : "1",
    "teams" : 
    [ 
        {
            "type" : "local",
            "isEnabled" : "true",
            "names" : 
            [ 
                { "name": "kumar","Nationality":"indian","BirthPlace":"Goa","Age":"U25" },
                { "name": "kannan","Nationality":"indian","BirthPlace":"Kerala","Age":"U25"}
            ]
        },
        {
            "type" : "national",
            "isEnabled" : "true",
            "names" : 
            [ 
                { "name": "kumar","Nationality":"indian","BirthPlace":"Goa","Age":"U25" },
                { "name": "kannan","Nationality":"indian","BirthPlace":"Kerala","Age":"U25"}
            ]
        },
        {
            "type" : "international",
            "isEnabled" : "true",
            "names" : 
            [ 
                { "name": "kumar","Nationality":"indian","BirthPlace":"Goa","Age":"U25" },
                { "name": "kannan","Nationality":"indian","BirthPlace":"Kerala","Age":"U25"}
            ]
        },
    ]
}

I have multiple docs in the same format in a mongodb collection.我在 mongodb 集合中有多个格式相同的文档。 I wanted to append the below lines into names array also only for "type: local" in each docs of the collections.我想将 append 以下行放入名称数组中,也仅适用于 collections 的每个文档中的“类型:本地”。 I tried $push and its appending in all teams array as i am finding difficulty to add this condition only for "type":"local"我尝试了 $push 及其在所有团队数组中的附加,因为我发现很难仅为“type”添加此条件:“local”

{ "name":"jack","Nationality":"indian","BirthPlace":" "Karnataka","Age":"U25" } {“姓名”:“杰克”,“国籍”:“印度人”,“出生地”:“卡纳塔克邦”,“年龄”:“U25”}

You can use positional operator: $[]您可以使用位置运算符:$[]

db.collection.update({
  "teams.type": "local"
},
{
  $push: {
    "teams.$[element].names": {
      "name": "jack",
      "Nationality": "indian",
      "BirthPlace": "Karnataka",
      "Age": "U25"
    }
  }
},
{
  arrayFilters: [
    {
      "element.type": "local"
    }
  ],
  multi: true
})

Try it here在这里试试

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

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