Java通过_id查询mongodb数据库

本文介绍MongoDB中_id字段的作用及三种不同的查询方法,包括使用DBObject、Bson过滤器及Document对象进行_id匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文以mongo-java-driver-3.5.0.jar为例

1 _id介绍:
MongoDB中存储的文档必须有一个”_id”键,其对应的”_id”值是由MongoDB服务器按照特定规律自动生成唯一的值,确保集合里面每个文档都能被唯一标识。这个键的值可以是任何类型的,默认是个ObjectId对象。

2 MongoDB查询语句:
db.user.find({ “_id” : ObjectId(“59c8cbea6157d6c78dab4ff0”) })
这里写图片描述

3 3中查询语句实现Java语句:

public static MongoCollection<Document> connect() {  
    @SuppressWarnings("resource")  
    MongoClient client = new MongoClient("127.0.0.1", 27017);  
    MongoDatabase db = client.getDatabase("test");  
    MongoCollection<Document> collection = db.getCollection("user");  
    return collection;
} 
public static List<Document> findBy1(DBObject filter) {  
    List<Document> results = new ArrayList<Document>();  
    FindIterable<Document> iterables = connect().find((Bson) filter);  
    MongoCursor<Document> cursor = iterables.iterator();  
    while (cursor.hasNext()) {  
        results.add(cursor.next());  
    }  

    return results;  
}

@Test
public void findById () {
    String _id = "59c8cbea6157d6c78dab4ff0";

    // 方法1
    DBObject filter = new BasicDBObject(); 
    filter.put("_id", new ObjectId(_id)); // 该写法在spring mvc + spring +hibernate项目中无效,具体原因不明确
    // filter.put("_id", _id); // 该写法在spring mvc + spring +hibernate项目中有效,具体原因不明确
    List<Document> results = findBy1(filter); 
    for(Document doc : results){  
        System.out.println("方法1:" + doc.toJson());  
        // 方法1:{ "_id" : { "$oid" : "59c8cbea6157d6c78dab4ff0" }, "name" : "yy", "password" : "123", "nickname" : "ygirl2", "iid" : 2 }
    } 

    // 方法2
    Bson filter2 =  Filters.and(Filters.eq("_id", new ObjectId(_id)));
    List<Document> results2 = findBy(filter2); 
    for(Document doc : results2){  
        System.out.println("方法2:" +doc.toJson());  
        // 方法2:{ "_id" : { "$oid" : "59c8cbea6157d6c78dab4ff0" }, "name" : "yy", "password" : "123", "nickname" : "ygirl2", "iid" : 2 }
    } 

    // 方法3
    Document filter3 = new Document(); 
    filter3.append("_id", new ObjectId(_id));
    List<Document> results3 = findBy(filter3); 
    for(Document doc : results3){  
        System.out.println("方法3:" +doc.toJson()); 
        // 方法3:{ "_id" : { "$oid" : "59c8cbea6157d6c78dab4ff0" }, "name" : "yy", "password" : "123", "nickname" : "ygirl2", "iid" : 2 } 
    } 
}
### Java 操作 MongoDB 数据库示例教程 #### 连接 MongoDB 数据库 为了建立与 MongoDB 的连接并执行基本的操作,可以使用 `mongo-java-driver` 包。通过此驱动程序,能够轻松地创建、读取、更新以及删除 MongoDB 中的数据。 ```java import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoDatabase; public class MongoConnection { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("testdb"); System.out.println("Connected to the database successfully"); } } ``` 这段代码展示了如何初始化客户端实例,并指定要使用的数据库名称[^1]。 #### 插入文档 向集合中插入新记录可以通过构建 `Document` 对象来实现: ```java import org.bson.Document; // ... MongoCollection<Document> collection = database.getCollection("users"); Document doc = new Document("username", "john_doe") .append("email", "johndoe@example.com") .append("age", 30); collection.insertOne(doc); System.out.println("Inserted document into the users collection."); ``` 这里定义了一个新的用户条目,并将其保存到了名为 “users” 的集合内。 #### 查询文档 利用 `find()` 方法可以从特定集合检索符合条件的文档列表;对于更复杂的查询需求,则推荐采用聚合管道 (`aggregate()`) 来处理多阶段过滤逻辑。 ```java FindIterable<Document> docs = collection.find(eq("username", "john_doe")); for (Document d : docs) { System.out.println(d.toJson()); } // 或者使用聚合函数进行复杂查询 AggregateIterable<Document> aggResults = collection.aggregate(Arrays.asList( Aggregates.match(Filters.eq("age", 30)), Aggregates.project(Projections.include("username")) )); aggResults.forEach(System.out::println); ``` 上述例子说明了两种不同的方式来进行简单匹配和高级组合条件下的搜索操作。 #### 更新现有文档 当需要修改已存在的记录时,可通过调用 `updateOne()/updateMany()` 函数指明目标筛选器及其对应的变更内容。 ```java Bson filter = eq("_id", doc.getObjectId("_id")); Bson updates = combine(set("email", "new.email@example.com"), inc("age", 1)); UpdateResult result = collection.updateOne(filter, updates); System.out.println("Matched count: " + result.getMatchedCount()); System.out.println("Modified count: " + result.getModifiedCount()); ``` 该片段演示了怎样定位单个实体并通过原子化指令集对其属性实施增量调整或替换动作[^5]。 #### 删除文档 最后,如果想要移除某些不再需要的信息项,只需应用相应的删除语句即可达成目的。 ```java DeleteResult delRes = collection.deleteOne(eq("username", "john_doe")); long deletedCount = delRes.getDeletedCount(); System.out.println(deletedCount + " documents were deleted from 'users' collection."); ``` 以上就是关于使用 Java 编程语言访问管理 MongoDB 资源的一些基础指导。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值