首先引入mongoDB的jar包
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.4</version>
</dependency>
</dependencies>
连接数据库:
MongoClient mongoClient = new MongoClient("localhost", 27017);
两个参数都可以不填,默认是localhost合27017
获取数据表
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
获取集合
MongoCollection<Document> collection = MongoDBUtil.getConnect().getCollection("user");
这几个方法可以进行封装方便使用
查询:
Bson filter = Filters.eq("name", "张三");
//指定查询过滤器查询
FindIterable findIterable = collection.find(filter);
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
添加
Document document = new Document("name","张三")
.append("sex", "男")
.append("age", 18);
//插入一个文档
collection.insertOne(document);
修改
Bson filter = Filters.eq("name", "张三");
//指定修改的更新文档
Document document = new Document("$set", new Document("age", 100));
//修改单个文档
collection.updateOne(filter, document);
注意,在新版mongoDB中,也许是更新策略变化,updateOne改用replaceOne使用