Home > Software design >  MongoDB - how I add a UUID column to existing collection based on values from current entries?
MongoDB - how I add a UUID column to existing collection based on values from current entries?

Time:07-15

I have 'Users' collection which has two columns, '_id' and 'userName', both of type string. I want to add third column 'UserId' which will be UUID wrapping the id from _id column.

Tried few ways but without any success.

For example:

{
_id: "fe83f869-154e-4c26-a5db-fb147728820f",
userName: "alex"
}

I want it to be:

{
_id: "fe83f869-154e-4c26-a5db-fb147728820f",
userName: "alex",
UserId: UUID("fe83f869-154e-4c26-a5db-fb147728820f")
}

I tried something like:

db.Users_temp.update(
  {},
  { $set: {"UserId": UUID("$_id") } },
  false,
  true
)

But it results in columns with value UUID("----")

Will appreciate any help.

CodePudding user response:

this will work

i am not sure why but this works only with set operation as an array rather than as a object

db.Users_temp.update({},[{$set: {'UserId': '$_id'}}])

CodePudding user response:

Ok,

Found a solution to my problem.

db.Users_temp.find().forEach(function(user) {
    db.Users_temp.update(
        {"_id" : user._id},
        { "$set": {"UserId": UUID(user._id)} }
    )
})
  • Related