If I try to insert a document in MongoDB with some key starting with $
I get an error message:
> db.x.insert({"a": {"$b": "1"}})
2016-09-29T21:14:23.078+0200 E QUERY [thread1] Error: field names cannot start with $ [$b] :
...
(I have observer a similar behaviour using Node.js driver)
However, running the following C++ program:
#include <cstdlib>
#include <iostream>
#include "mongo/client/dbclient.h" // for the driver
// compile with: g++ test.cpp -pthread -lmongoclient -lboost_thread -lboost_system -lboost_regex -o test
void run() {
mongo::DBClientConnection c;
c.connect("localhost");
mongo::BSONObj doc = BSON("a" << BSON("$b" << 1));
c.insert("test.x", doc);
}
int main() {
mongo::client::initialize();
try {
run();
} catch( const mongo::DBException &e ) {
std::cout << "caught " << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
I'm able to insert it, as find()
shows:
> db.x.find()
{ "_id" : ObjectId("57ed67fdbf3a716e16f6d102"), "a" : { "$b" : 1 } }
Thus, it seems that C++ driver is able to "bypass" the document structure rules described in MongoDB documentation. Is there any explanation for this behaviour? It could "break" MongoDB database in some way (I guess that that limitation is for a good reason and having documents in the DB not honoring it could be problematic)
I have observed that this happens only when the key with $
is not at first level. For example, if I use
mongo::BSONObj doc = BSON("$b" << 1);
then I get a consistent error
caught OperationException: { index: 0, code: 2, errmsg: "Document can't have $ prefixed field names: $b", op: { _id: ObjectId('57ed6a015365c193cbbb3231'), $b: 1 } }
Just in case it is needed, I'm using MongoDB 3.2.0 and legacy C++ driver 1.0.7