对于MongoDB的Java驱动, 从2.10.0版本后,文档中提醒Mongo类将会被废除,现在开始都鼓励使用MongoClient类。
下面演示一个Java程序如何使用最新的MongoClient类来对MongoDB写操作。
首先假定已经有了一个Replica-set集群,分别是d1, d2和 d3三台虚拟机。
然后创建一个Maven构建的Java应用程序。使用了maven exec plugin用来方便执行jar包和定制参数。
看一下pom.xml:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <goals> <goal>java</goal> </goals> </execution> </executions> <configuration> <mainClass>org.freebird.dbtool.App</mainClass> <arguments> <argument>d1,d2,d3</argument> </arguments> </configuration> </plugin> </plugins> </build>
看看代码初始化部分:
public static void main(String[] args) throws UnknownHostException { System.out.println(args[0]); String[] hosts = args[0].split(","); int portNumber = 27017; System.out.println(hosts[0]); System.out.println(hosts[1]); System.out.println(hosts[2]); MongoClient client = new MongoClient(Arrays.asList(new ServerAddress(hosts[0], portNumber), new ServerAddress(hosts[1], portNumber), new ServerAddress(hosts[2], portNumber))); MyApp.getInstance().setDbName("kaimei"); MyApp.getInstance().setClient(client);
同时创建了一个MyApp的singleton对象,存放这个MongoClient对象,并提供了getDB()方便日后获取数据库连接。
public class MyApp { private MyApp() { } public static MyApp getInstance() { return MyAppHolder.INSTANCE; } private static class MyAppHolder { private static final MyApp INSTANCE = new MyApp(); } @Getter @Setter String dbName; @Setter MongoClient client; public DB getDB() { return client.getDB(dbName); } }
public static void bind(final String address, final String userId) { DB db = MyApp.getInstance().getDB(); DBCollection collection = db.getCollection(DISPLAY_COLLECTION); DBObject condition = new BasicDBObject(); condition.put("address", address); DBObject field = new BasicDBObject(); field.put("user_id", new ObjectId(userId)); DBObject set = new BasicDBObject(); set.put("$set", field); collection.update(condition, set, false, false); }