Home > Software engineering >  Replace field in mongo db database
Replace field in mongo db database

Time:12-28

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?

CodePudding user response:

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
    }
})

CodePudding user response:

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

  • Related