问题
I'm accessing a MongoDB and want to reuse typical command line queries also within Java. I know it is possible to use the BasicDBObject, but I want to use command line queries like this:
db.MyCollection.find()
I tried now using the command() method of the database:
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));
But this returns me the following result.
"ok": 0,
"code": 59,
"errmsg": "no such cmd: db.MyCollection.find()",
"bad cmd": {"db.MyCollection.find()": true},
"serverUsed": "localhost:27017"
How can I run a command line query within Java?
I do not want to use the DBCollection class - because then it's not anymore possible to run queries for different collections.
DBCollection collection = db.getCollection("MyCollection");
collection.find(); //NOT THIS
回答1:
I don't think you can do that. With db.command()
you are limited to these commands. Maybe you could get something like this to work (I'm having problems with getting expected results)
final DBObject command = new BasicDBObject();
command.put("eval", "function() { return db." + collectionName + ".find(); }");
CommandResult result = db.command(command);
BTW, why don't you use chained calls like db.getCollection(collectionName).find();
to avoid sticking to one collection?
来源:https://stackoverflow.com/questions/26384277/command-line-query-within-java