MongoDB Insert key with '$' (dollar)

后端 未结 1 1643
遇见更好的自我
遇见更好的自我 2021-01-03 04:08

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

1条回答
  •  伪装坚强ぢ
    2021-01-03 04:32

    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"), "." : "$" }
    

    0 讨论(0)
提交回复
热议问题