简体   繁体   中英

Replace field in mongo db database

Helloo guys,

i have in mongo db collection:

{
    "_id" : "aghpbF6xxxCyMGg9J",
    "description" : "",
    "name" : "test",
    "roles" : [ 
        "ab.read", 
        "test.view"
    ],
    "type" : "group"
}

and i have testRoles object:

[ { name: 'testRoles',
permissions: [ 'ab.write', 'test.check' ] } ],

and basically what i need to do is, replace field roles in db with field permissions from testRoles object, please anybody can help me manage it please?

You can simply $set the desired field and replace the entire array like this:

db.collection.updateOne(
{} //  empty match since idk what your match parameter is ;)
,{
    $set: {
        "roles": ['a', 'b'] // this is your value from the object
    }
})

for role in testRoles: db.collection.update_many.update_one({'name': role['name']},{$set: {'roles': role['permission']}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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