MongoDB使用'$'插入密钥(美元)

时间:2016-11-11 06:29:30

标签: mongodb mongodb-query

我正在尝试插入一个带有json对象的集合,该对象包含一个以“$”开头的键(例如:'$count')。我读过mongodb v3.0 FAQ's,他们已经提到它不是一个关键。是否有任何迂回方式插入这样的钥匙并将其取回?

1 个答案:

答案 0 :(得分:5)

  

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. “.”).

不是重新编目,但你可以试试这个:

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