MQL for update many with a new field from existing document

Hi Guys

what would a correct query look like to perform this:

db.employees.updateMany({}, {$set : {“new_field”:"$privileges"}},
{upsert:false,
multi:true})

All attempts places the “stringvalue” and not the field equivalent in the new_field.

on a simple schema like this :

{ _id: ObjectId("604fbebd435c984410df951c"),
    name: 'Martin',
    age: 43,
    phone: { personal: '555-123-123', work: '555-456-456', ext: '5623' },
    privileges: 'user',
    favorites: { food: 'pizza', artist: 'Picasso' },
    finished: [ 18, 12 ],
    badges: [ 'black', 'blue' ],
    points: [ { points: 78, bonus: 8 }, { points: 57, bonus: 7 } ],
    SecurityLog: 
     [ { Date: 2021-03-15T20:26:56.041Z,
         levelgranted: '$ROOT.privileges' } ],
    SecurityLog2: [ { date: '$NOW', level: 'user' } ],
    Headoffice: { CompanyName: 'MangoHQ', city: 'Cork' },
    adress: [ 'Military hill', 'Cork', 'Ireland' ],
    new_field: '$privileges' } ]

Welcome to the community Miroslaw,

Starting from MongoDB 4.2 you can update with aggregation pipeline, which allows the use of other fields to update a field.

good luck

1 Like

Hi, i dont to aggregate a find, I want to add a field with an update, i want to UPDATE the original document with a combination from the $$ROOT document to create a new value pair… Please review my question and you will notice and understand my question…
updateMany({}, {$set : {“new_field”:"$privileges"}},

In short, try this:

db.members.update( { },
   [
      { $set: { new_field: "$privileges" } }
   ],
   { multi: true })

Hope that solves your issue
ps: this is not the aggregation framework, it’s still an update

Hi,
so basically u took my query and took out the upsert?

this is not working… hence im asking for assistance…
this community is not as active i see

Hi,

not really
please check the documentation. you used a document as an update parameter:

{$set : {“new_field”:"$privileges"}}

I used a pipeline with one stage

[
    { $set: { new_field: "$privileges" } }
]

which allows the use of other fields values
By default, upster is set to false

It works, at least for me:

try a similar scenario on the web shell and share the screenshot of what you get

Most of the members are volunteers. If you are looking for professional support, please refer to https://support.mongodb.com/

good luck

1 Like

image

finally worked once i compared the code.
MongoSH warns that update is deprecated.

1 Like