如何在现有文档中更新新数组

时间:2019-07-09 10:34:37

标签: mongodb mongodb-query

我正在收集以下mongo文档,现在我的问题是我想在现有文档中插入新数组,我是mongodb的新手,请根据我的要求发布您的代码。

{
    "schoolID" : "5ca5e1915e6f66641efasr",
    "settings" : {
        "sportsAllowed" : true
    }
},
{
    "schoolID" : "5ca5e1915e6f623466ef3a",
    "settings" : {
        "sportsAllowed" : true
    }
}
  

下面的数组需要添加我现有的文档

"Sports": [
               {
               "class": "1",
               "name": "Cricked"
               },
              { 
                "class": "2",
               "type": "Football"
              }
        ]
  

预期产量

{
    "schoolID" : "5ca5e1915e6f66641efasr",
    "settings" : {
        "sportsAllowed" : true,
        "Sports": [
               {
               "class": "1",
               "name": "Cricked"
               },
              { 
                "class": "2",
               "type": "Football"
              }
        ]
    }
},
{
    "schoolID" : "5ca5e1915e6f623466ef3a",
    "settings" : {
        "sportsAllowed" : true,
        "Sports": [
               {
               "class": "1",
               "name": "Cricked"
               },
              { 
                "class": "2",
               "type": "Football"
              }
        ]
    }
}
  

我的代码

var value=[
    {
        "class": "1",
        "name": "Cricked"
    },
    { 
        "class": "2",
        "type": "Football"
    }
]

db.Colleges.update({},{
    $set : {
        "Sports": value
    }
},{multi:true})

2 个答案:

答案 0 :(得分:0)

您可以使用无任何匹配条件的更新,也可以使用val source1 = Observable.just(1,2,3) val source2 = Observable.just("A", "B", "C") source1.withLatestFrom(source2) { intValue: Int, stringValue: String, stringResult: String -> "Result string: $intValue $stringValue"} 更新集合中的所有文档。

尝试一下:

multi:true

答案 1 :(得分:0)

let updateWith = {
    'settings.Sports': [
        {
            "class": "1",
            "name": "Cricked"
        },
        {
            "class": "2",
            "type": "Football"
        }
    ]
}
let updateWhere = {}
collection_name.update(updateWhere, { $set: updateWith }, { multi: true }, function (err, affected) {
})
OR..................
let updateWith = [
    {
        "class": "1",
        "name": "Cricked"
    },
    {
        "class": "2",
        "type": "Football"
    }
]
collection_name.update(updateWhere, { $set: { 'settings.Sports': updateWith } }, { multi: true }, function (err, affected) {
})