1.使用maven安装驱动(也可以手动下载jar包导入项目):
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.0</version> </dependency>
2.连接mongodb得到MongoClient
// To directly connect to a single MongoDB server
// (this will not auto-discover the primary even if it's a member of a replica set)
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
MongoClient mongoClient = new MongoClient(
Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
// or use a connection string
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
MongoClient mongoClient = new MongoClient(connectionString);
3.CRUD操作
// insert
Document $doc
= new Document("_id", "abcd").append("name", "xiaoming");
mongoClient().getDatabase(database).getCollection(collection).insertOne($doc);
// delete
mongoClient().getDatabase(db).getCollection(coll).deleteOne(new Document("_id", "abcd"));
// find
Document doc = mongoClient().getDatabase(database).getCollection(collection).find(new Document("name", "xiaoming")).first();
System.out.println(doc);
// update
mongoClient().getDatabase(database).getCollection(collection).updateOne(new Document("_id", "abcd"), new Document("$set", new Document("name", "xiaowu")));
// close
mongoClient.close();