我正在访问 MongoDB,并且希望在 Java 中重用典型的命令行查询。
我知道可以使用 BasicDBObject,但我想使用如下命令行查询:
db.MyCollection.find()
我现在尝试使用数据库的 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));
但这返回给我以下结果。
"ok": 0,
"code": 59,
"errmsg": "no such cmd: db.MyCollection.find()",
"bad cmd": {"db.MyCollection.find()": true},
"serverUsed": "localhost:27017"
如何在 Java 中运行命令行查询?
我不想使用 DBCollection 类 - 因为那样就不再可能对不同的集合运行查询。
DBCollection collection = db.getCollection("MyCollection");
collection.find(); //NOT THIS
我认为你做不到。和db.command()
你仅限于这些命令 http://docs.mongodb.org/manual/reference/command/。也许你可以得到这样的东西来工作(我在获得预期结果方面遇到问题)
final DBObject command = new BasicDBObject();
command.put("eval", "function() { return db." + collectionName + ".find(); }");
CommandResult result = db.command(command);
顺便说一句,你为什么不使用像这样的链式调用db.getCollection(collectionName).find();
以避免坚持一个集合?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)