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