Java command line query

I am turning to MongoDB and want to reuse typical command line queries in Java as well. I know that you can use BasicDBObject, but I want to use command line queries as follows:

db.MyCollection.find()

I tried now to use the database command () method:

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 to run a command prompt in java?

I do not want to use the DBCollection class, because now it is no longer possible to run queries on different collections.

DBCollection collection = db.getCollection("MyCollection");
collection.find(); //NOT THIS
+2
source share
1 answer

, . db.command() . , - ( )

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

, , db.getCollection(collectionName).find();, ?

+4

All Articles