6

I am trying to insert a collection with a json object containing a key which starts with '$' (for instance: '$count'). I read the mongodb v3.0 FAQ's and they have mentioned it is not such a key. Is there any roundabout way insert such a key and retrieve it back?

sergiuz
  • 5,353
  • 1
  • 35
  • 51
AbiSivam
  • 419
  • 1
  • 6
  • 17
  • I've provided a solution here: https://stackoverflow.com/questions/12397118/mongodb-dot-in-key-name/52651208#52651208 – Nico Oct 04 '18 at 16:15

1 Answers1

8

Field names cannot contain dots (i.e. .) or null characters, and they must not start with a dollar sign (i.e. $).


In some cases, you may wish to build a BSON object with a user-provided key. In these situations, keys will need to substitute the reserved $ and . characters. Any character is sufficient, but consider using the Unicode full width equivalents: U+FF04 (i.e. “$”) and U+FF0E (i.e. “.”).

Is not recomanded but you can try this:

dollar = "\uFF04";
$
dot = "\uFF0E"
.

db.test.save({[dollar]:dot})
WriteResult({ "nInserted" : 1 })
db.test.save({[dot]:dollar})
WriteResult({ "nInserted" : 1 })

db.test.find()
{ "_id" : ObjectId("58256b0f9934a5d1c696c456"), "$" : "." }
{ "_id" : ObjectId("58256d359934a5d1c696c457"), "." : "$" }
sergiuz
  • 5,353
  • 1
  • 35
  • 51
  • Could you please elaborate the snippet on how we can use? – AbiSivam Nov 11 '16 at 09:29
  • 1
    Essentially you go through all your values converting $ or . to it's unicode representation as shown in the snippet – Sammaye Nov 11 '16 at 10:10
  • 1
    That is not the "true" dollar character. The usual dollar character is "\u0024", while the character "\uFF04" is a character "similar" to the "true" dollar character. Hence, if you want to store some working update queries in a collection, such as { $set: { name: 'Gianni' } }, you can not, because with that character they would not work. Also try to do ('\uFF04" === '$') in a js console and it will return false. – EuberDeveloper Dec 07 '20 at 21:14