Search code examples
mongodbmongo-shell

Using UpdateMany to Add a New Field With The Value of Another Field as a String


I'm trying to add a new field to all of my documents that contains the value of a number field, but as a string instead (in an effort to do both a rename and a type change for that field).

I tried this:

db.person.updateMany({}, {$set: { userId: {$toString:"$snowflake"} }})

Which gave me this:

the userId was instead added as an object

I've also tried just doing this:

db.person.updateMany({}, {$set: { userId:"$snowflake" }})

Which just inserted the value as "$snowflake". Everything I've seen suggests using existing fields this way, is there something I'm doing wrong?

MongoDB 6.0.6 Enterprise


Solution

  • The $toString in your query as a field because it is not used within an aggregation pipeline [], hence creating an userId as an object with $toString as a field in it.

    Solution

    Update your query as:

    db.person.updateMany(
      {},
      [
        {
          $set: {
            userId: { $toString: "$snowflake" }
          }
        }
      ]
    )