Java中的命令行查询

4

我正在访问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

你为什么要用一个容易受到注入攻击的API来替换一个完全安全的API呢?除了个人对语法的偏好之外,你有没有其他充分的理由呢? - Philipp
是的,我想为我们非Java软件提供一个小型API - 它没有mongodb接口。因此,我需要有一个类来运行不同的查询。 - Philipp
1个回答

6

我认为你做不到。使用db.command(),你的操作受到限制,只能使用这些命令。也许你可以尝试这个方法(但是我无法得到预期结果)。

    final DBObject command = new BasicDBObject();
    command.put("eval", "function() { return db." + collectionName + ".find(); }");
    CommandResult result = db.command(command);

顺便问一下,为什么不使用链式调用,比如db.getCollection(collectionName).find();,以避免只针对一个集合进行操作?


出现异常 "Caused by: com.mongodb.MongoCommandException: Command failed with error 13: 'not authorized on bapdocdb_pricing to execute command { eval:.... on server ...:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on bapdocdb_pricing to execute command { eval: "..." }", "code" : 13, "codeName" : "Unauthorized" }。 - myuce
2
@myuce 这个能帮到你吗?链接 - Predrag Maric
谢谢Predrag,我采用了较为困难的方式并开始使用聚合函数 :)。 - myuce
@Anshul 不知道,抱歉。我已经很久没和 MongoDB 工作了。 - Predrag Maric
如此回答 https://dev59.com/eInda4cB1Zd3GeqPENHZ#61952470,eval在4.2中已被删除。使用Java Driver不再有这样的方法。 - loicmathieu
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接