Java中的命令行查询

问题描述 投票:4回答:1

我正在访问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
java mongodb generic-collections
1个回答
6
投票

我认为您无法做到。使用db.command(),您将被限制为these commands。也许您可以使类似的东西起作用(我在获得预期结果方面遇到问题)

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

顺便说一句,为什么不使用db.getCollection(collectionName).find();之类的链接调用来避免坚持一个集合?

© www.soinside.com 2019 - 2024. All rights reserved.