我必须使用Java驱动程序(<3.0.0版本)在集合system.js
中插入一个javascript函数system.js
是MongoDB的一个特殊集合,用于存储javascript函数以供重用。我需要存储此函数才能将其与map/reduce命令一起使用。
从MongoDB shell我使用:
db.system.js.save(
{
_id: "echoFunction",
value : function(x) { return x; }
}
)
使用Java驱动程序,我尝试以字符串的形式插入函数值:
try{
MongoClient mongoclient = new MongoClient(HOST,PORT);
DB db = mongoclient.getDB("test");
System.out.println("Succesfully connected to MongoDB");
DBCollection jsColl = db.getCollection("system.js");
DBObject doc = new BasicDBObject("_id","echoFunction").append("value","function(x) {return x}");
jsColl.insert(doc);
}
DBObject doc
被正确地添加到system.js
集合中,但我的函数在MongoDB中被视为String,而不是javascript函数,因此我无法将其与map/reduce命令一起使用。
您必须将Object作为org.bson.types.Code放入类似的值中
Code functionCode = new Code ("function(x) {return x}") ;
DBObject doc = new BasicDBObject("_id","echoFunction").append("value",functionCode);