Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-56462

Field starting with dollar in an embedded document cannot be updated with $set

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 4.4.1
    • Component/s: None
    • None
    • ALL

      I have a document in MongoDB (version 4.4.1) in a collection with a document which has a field `x` which value is an embedded document, created this way:

      > db.c.insert({_id: 1, x: {$a: 2, b: 3}})
      WriteResult({ "nInserted" : 1 })
      > db.c.findOne({_id: 1})
      { "_id" : 1, "x" : { "$a" : 2, "b" : 3 } } 

      Note there is a field in the embedded document which starts with dollar (`$a`) and a field that doesn't start with dollar (`b`). I can update the field without dolar without problem:

      > db.c.updateOne({_id: 1}, {$set: {"x.b": 30}})
      { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
      > db.c.findOne({_id: 1})
      { "_id" : 1, "x" : { "$a" : 2, "b" : 30 } } 

      However, if I try to update the field which starts with dollar in the same way, I get an error

      > db.c.updateOne({_id: 1}, {$set: {"x.$a": 20}})
      WriteError({
          "index" : 0,
          "code" : 52,
          "errmsg" : "The dollar ($) prefixed field '$a' in 'x.$a' is not valid for storage.",
          "op" : {
              "q" : {
                  "_id" : 1
              },
              "u" : {
                  "$set" : {
                      "x.$a" : 20
                  }
              },
              "multi" : false,
              "upsert" : false
          }
      })

      I know the recomendation in MongoDB documentation https://docs.mongodb.com/manual/reference/limits/#mongodb-limit-Restrictions-on-Field-Names which says:

      The MongoDB Query Language cannot always meaningfully express queries over documents whose field names contain these characters  [$ or .]... Until support is added in the query language, the use of $ and . in field names is not recommended and is not supported by the official MongoDB drivers.

      However, note this case the problem is not in the query part but in the update part, so my understanding is that that recommendation doesn't apply. Moreover, if I do a query like

      db.c.find({"x.$a": 2}) 

      it works.

            Assignee:
            edwin.zhou@mongodb.com Edwin Zhou
            Reporter:
            fermin.galanmarquez@telefonica.com Fermín Galán
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: