注册

java操作mongodb实现CURD功能实例

  1. Java操作MongoDB实现CURD功能示例

在Java应用程序中使用MongoDB进行CURD操作,需要依赖MongoDB Java驱动包,可以使用Maven进行依赖管理。本示例以Maven项目演示MongoDB的CURD操作,具体步骤如下:

步骤1:添加Maven依赖


    org.mongodb
    mongo-java-driver
    3.12.7

步骤2:连接MongoDB

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoClient.getDatabase("testdb");

步骤3:插入数据

MongoCollection collection = db.getCollection("testcol");
Document document = new Document();
document.append("name", "张三").append("age", 30);
collection.insertOne(document);

步骤4:查询数据

MongoCollection collection = db.getCollection("testcol");
Document query = new Document();
query.append("name", "张三");
FindIterable result = collection.find(query);
for (Document doc : result) {
    System.out.println(doc.toJson());
}

步骤5:更新数据

MongoCollection collection = db.getCollection("testcol");
Document query = new Document().append("name", "张三");
Document update = new Document().append("$set", new Document("age", 31));
UpdateResult result = collection.updateOne(query, update);
System.out.println(result.getModifiedCount());

步骤6:删除数据

MongoCollection collection = db.getCollection("testcol");
Document query = new Document().append("name", "张三");
DeleteResult result = collection.deleteOne(query);
System.out.println(result.getDeletedCount());
  1. Java使用MongoDB实现自增序列

在MongoDB中,不像关系型数据库那样自带自增序列(Auto Increment),如果需要使用自增序列,可以通过在MongoDB中维护一个包含当前序列值的集合,然后通过CAS(Compare-And-Swap)的方式进行更新。下面是Java实现自增序列的代码示例:

步骤1:创建自增序列的集合

db.counters.insertOne({_id: "order_sequence", sequence_value: 1})

步骤2:获取自增序列的值

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoClient.getDatabase("testdb");
MongoCollection collection = db.getCollection("counters");
Document filter = new Document("_id", "order_sequence");
Document update = new Document("$inc", new Document("sequence_value", 1));
Document result = collection.findOneAndUpdate(filter, update);
System.out.println(result.getInteger("sequence_value"));

步骤3:使用自增序列的值

MongoCollection collection = db.getCollection("orders");
Document order = new Document("_id", result.getInteger("sequence_value"))
                .append("amount", 100);
collection.insertOne(order);