skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search