Java中的命令行查询

Java中的命令行查询,java,mongodb,generic-collections,Java,Mongodb,Generic Collections,我正在访问MongoDB,并希望在Java中重用典型的命令行查询。 我知道可以使用BasicDBObject,但我希望使用如下命令行查询: db.MyCollection.find() 我现在尝试使用数据库的command()方法: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("MyDatabase"); CommandResult result= db.com

我正在访问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()。也许你可以让这样的东西发挥作用(我在获得预期结果方面遇到了问题)


顺便说一句,为什么不使用像
db.getCollection(collectionName).find()这样的链式调用为了避免粘在一个集合上?

为什么要用一个完美保存的API替换一个易受注入攻击的API?除了个人对语法的偏好之外,你有什么好的理由吗?是的,我想为我们的非基于java的软件提供一个小API,它没有mongodb接口。因此,我需要一个可以运行不同查询的类。获取异常“由以下原因引起:com.mongodb.MongoCommandException:命令失败,错误13:'未授权在bapdocdb_上执行命令{eval:…..在服务器上执行命令…”:27017。完整响应为{“确定”:0.0,“errmsg”:“未授权在bapdocdb_上执行命令”{eval:\“…\”},“code”:13,“codeName”:“Unauthorized”}@myuce确实有帮助吗?谢谢Predrag,使用了艰难的方法并开始使用聚合函数:)。@PredFragmaric现在eval已被弃用,还有其他方法吗this@Anshul不知道,抱歉,很久没有和mongodb合作了。
    final DBObject command = new BasicDBObject();
    command.put("eval", "function() { return db." + collectionName + ".find(); }");
    CommandResult result = db.command(command);