mongodbmongo-shell

Mongosh: Reference to field does not get resolved


I am trying to update my campaigns collection with the following command:

db.campaigns.updateMany(
  { _id: ObjectId("65b1b0dd6182c1dfe906f3be") },
  {
    $set: {
      "status": "$created_by",
      "is_active_new": "$is_active.type",
    }
  }
)

when I run this command, status is literally set to "$created_by" and the value is not resolved. As per my understanding , it should have the actual value of $created_by field and not the literal string. Same goes for the $is_active_new as well.

MongoDb version is 6.0.12 Enterprise.


Solution

  • As mentioned in the comment you need an aggregation pipeline. In your case you need only to add the brackets []:

    db.campaigns.updateOne(
      { _id: ObjectId("65b1b0dd6182c1dfe906f3be") },
      [{
        $set: {
          "status": "$created_by",
          "is_active_new": "$is_active.type",
        }
      }]
    )
    

    Note, _id is the primary key, thus updateMany does not make much sense. (But in fact it does not make any difference in your case)