在java中使用MongoDB runCommand方法

yeotifhr  于 2022-12-18  发布在  Go
关注(0)|答案(2)|浏览(203)

如何在java中使用MongoDB runCommand方法?我在mongoDB控制台中使用这个db.runCommand( { explain: { update: "info.asset", updates: [ { q: { "version": 3,"providerAssetId":"123" }, u: { $set: { "version": 9 } }, hint: { providerAssetId: 1, version: -1 } }] }, verbosity: "executionStats" }),但是我想在Java中使用这个命令,谁能告诉我如何在Java中使用这个命令?
我使用的是mongo-java-driver-3.3.0.jar
谢谢
示例:

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

我可以用explain来查找方法,但是我不知道如何在java中使用explain来更新方法

zmeyuzjn

zmeyuzjn1#

我记得,大多数方法不再支持explain,您可以在java中使用与shell中完全相同的RunCommand method

7jmck4yq

7jmck4yq2#

假设您有MongoClientMongoDatabaseMongoCollection

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

你想执行db.runCommand(...)这个命令应该在数据库级别上执行(而不是在集合上),这意味着你必须像这样调用smth:

...
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);

相关问题