Home > front end >  Using the MongoDB runCommand method in java
Using the MongoDB runCommand method in java

Time:12-15

How to use MongoDB runCommand method in java? i'm using this db.runCommand( { explain: { update: "info.asset", updates: [ { q: { "version": 3,"providerAssetId":"123" }, u: { $set: { "version": 9 } }, hint: { providerAssetId: 1, version: -1 } }] }, verbosity: "executionStats" }) in mongoDB console, But I want to use this command in Java, can any one suggest me how to use this in Java?

I'm using mongo-java-driver-3.3.0.jar

thank you

example :

DBObject explain = coll.find(condition).sort(order).limit(count).explain();

I can use explain for find method, but I don't know how to use explain on update method in java

CodePudding user response:

As I recall, explain is not supported anymore for most of methods. You can use fully the same RunCommand method in java as in the shell

CodePudding user response:

Let's say you have MongoClient, MongoDatabase and MongoCollection:

MongoClient client = //here init connection
MongoDatabase db = client.getDatabase("DbNameHere");
MongoCollection collection = db.getCollection("CollectionNameHere");

you want to execute db.runCommand(...) this command should be executed on db level (not on collection), it means you have to call smth like this:

...
MongoDatabase db = client.getDatabase("DbNameHere");
Document command = new Document("explain",
            new Document("update", "info.asset")
                .append("updates", List.of(
                        new Document("q", Filters.and(
                            Filters.eq("version", 3),
                            Filters.eq("providerAssetId", "123"))
                        )
                        .append("u", Updates.set("version", 9))
                        .append("hint", new Document("providerAssetId", 1)
                            .append("version", -1)
                        )
                    )
                )
                .append("verbosity", "executionStats")
        );
db.runCommand(command);

  • Related