正如标题所示,我想获取客户端连接的 mongo 实例的版本。目前我正在使用 mongo java 驱动程序 2.9.3,而 mongo 实例是 2.2.2。
我需要这样做,以便同时支持函数$pushAll
和函数,因为前者已从 2.4 版中弃用,而支持后者。总之我想知道Java驱动程序相当于$push
$each
db.version()
在未来版本的驱动程序提供一种方法之前,目前的解决方案正在遵循,这要归功于此处的提示。
DB db = new Mongo("127.0.0.1").getDB("test");//Better use MongoClient since Mongo class is deprecated
System.out.println(db.getMongo().getVersion());//prints 2.9.3 driverversion
CommandResult commandResult = db.command("buildInfo");
System.out.println(commandResult.getString("version"));//prints 2.4.2 Note tried at home since my mongo version is 2.4.2
稍微摸索一下就发现了这一点:
> db.version()
2.4.6
> db.version
function (){
return this.serverBuildInfo().version;
}
> db.serverBuildInfo
function (){
return this._adminCommand( "buildinfo" );
}
> db.runCommand('buildinfo')
{
"version" : "2.4.6",
"gitVersion" : "b9925db5eac369d77a3a5f5d98a145eaaacd9673",
"sysInfo" : "Linux ip-10-2-29-40 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_49",
"loaderFlags" : "-fPIC -pthread -rdynamic",
"compilerFlags" : "-Wnon-virtual-dtor -Woverloaded-virtual -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -pipe -fno-builtin-memcmp -O3",
"allocator" : "tcmalloc",
"versionArray" : [
2,
4,
6,
0
],
"javascriptEngine" : "V8",
"bits" : 64,
"debug" : false,
"maxBsonObjectSize" : 16777216,
"ok" : 1
}
所以你可以runCommand
在你的java代码中使用等价物(不知道java驱动程序,我是红宝石人)。
这对我有用(Java 客户端 3.5.0):
MongoClient client = //..
String version = client.getDatabase("dbname")
.runCommand(new BsonDocument("buildinfo", new BsonString("")))
.get("version")
.toString();
这就是我所做的:
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase db = mongoClient.getDatabase("test");
Document document = db.runCommand(new Document("buildInfo",1));
System.out.println("MongoDB Version: "+document.getString("version"));
我的配置
- MongoDB JVM 驱动程序:4.1
- JDK 11