public class MongoDBExample {
private MongoClient client;
private MongoDatabase database;
private MongoCollection<Document> collection;
public MongoDBExample() {
// 创建MongoDB连接
client = new MongoClient("localhost", 27017);
// 连接Database和Collection
database = client.getDatabase("test");
collection = database.getCollection("users");
}
public void insert() {
// 插入单条数据
Document doc = new Document("name", "Alice").append("age", 21).append("city", "Beijing");
collection.insertOne(doc);
// 插入多条数据
List<Document> docs = Arrays.asList(
new Document("name", "Bob").append("age", 22).append("city", "Shanghai"),
new Document("name", "Charlie").append("age", 23).append("city", "Guangzhou")
);
collection.insertMany(docs);
}
public void find() {
// 查询单条数据
Document doc = collection.find(eq("name", "Alice")).first();
System.out.println(doc.toJson());
// 查询多条数据
FindIterable<Document> iterable = collection.find(and(gte("age", 22), lt("age", 25)));
for (Document d : iterable) {
System.out.println(d.toJson());
}
}
public void update() {
// 更新单条数据
collection.updateOne(eq("name", "Alice"), new Document("$set", new Document("age", 25)));
// 更新多条数据
collection.updateMany(and(gte("age", 22), lt("age", 25)), new Document("$inc", new Document("age", 1)));
}
public void delete() {
// 删除单条数据
collection.deleteOne(eq("name", "Alice"));
// 删除多条数据
collection.deleteMany(and(gte("age", 22), lt("age", 25)));
}
public void close() {
// 关闭MongoDB连接
client.close();
}
public static void main(String[] args) {
MongoDBExample example = new MongoDBExample();
example.insert();
example.find();
example.update();
example.delete();
example.close();
}
}
在这个示例中,我们使用了MongoDB Java Driver来完成对MongoDB的数据库操作。在构造方法中,我们创建MongoDB连接并连接指定的Database和Collection。然后我们分别实现了插入、查询、更新和删除数据的方法,并在最后的main()方法中对这些方法进行调用。需要注意的是,当我们完成对MongoDB的所有操作后,需要调用close()方法来关闭MongoDB连接。
以上是一个MongoDB完整使用的代码示例,但实际应用中可能还需要进一步优化和完善,以适应具体业务场景的需求。