Fiv*_*veO 4 java mongodb generic-collections
我正在访问MongoDB,并希望在Java中重用典型的命令行查询.我知道可以使用BasicDBObject,但我想使用这样的命令行查询:
db.MyCollection.find()
Run Code Online (Sandbox Code Playgroud)
我现在尝试使用数据库的command()方法:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("MyDatabase");
CommandResult result= db.command("db.MyCollection.find()");
JSONObject resultJson = new JSONObject(result.toString());
System.out.println(resultJson.toString(4));
Run Code Online (Sandbox Code Playgroud)
但这会给我带来以下结果.
"ok": 0,
"code": 59,
"errmsg": "no such cmd: db.MyCollection.find()",
"bad cmd": {"db.MyCollection.find()": true},
"serverUsed": "localhost:27017"
Run Code Online (Sandbox Code Playgroud)
如何在Java中运行命令行查询?
我不想使用DBCollection类 - 因为它不再可能为不同的集合运行查询.
DBCollection collection = db.getCollection("MyCollection");
collection.find(); //NOT THIS
Run Code Online (Sandbox Code Playgroud)
我认为你不能这样做.随着db.command()您仅限于这些命令.也许你可以得到这样的东西工作(我遇到了获得预期结果的问题)
final DBObject command = new BasicDBObject();
command.put("eval", "function() { return db." + collectionName + ".find(); }");
CommandResult result = db.command(command);
Run Code Online (Sandbox Code Playgroud)
顺便说一句,为什么不使用链式调用db.getCollection(collectionName).find();来避免粘贴到一个集合?