Java中的命令行查询

我正在访问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()您只能使用这些命令 。 也许你可以得到这样的东西工作(我遇到了获得预期结果的问题)

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

顺便说一句,为什么不使用链接调用,如db.getCollection(collectionName).find(); 避免粘在一个集合上?

Interesting Posts