btbenjamin
btbenjamin

Reputation: 873

MongoDb : Copy a field using update and $set

I'm using Mongo version 4.4.7. And i trying to copy a field in other field :

db.getCollection('UserAccount').update(
         { }, 
         { $set:  {'Profile.Email' : '$UserName'}}, 
         false,  
         true 
)

// Result Profile.Email : "$UserName" 
// I want Profile.Email : "[email protected]"

Mongo copy the string "$UserName" and not the value of this variable.

But when i execute aggregate it's work perfectly, But in my case i want an update :

db.getCollection('UserAccount').aggregate( [
         
    {$set: {'Profile.Email' : '$UserName'} }
    
])

Any idea of this?

Upvotes: 0

Views: 45

Answers (1)

J.F.
J.F.

Reputation: 15187

You can use an aggregation into an update using [] (check this link) like this:

db.collection.update({},
[  <-- Start aggregation
  {
    "$set": {
      "Profile.Email": "$UserName"
    }
  }
])

Example here

Upvotes: 1

Related Questions