1. 程式人生 > >Java通過_id查詢mongodb資料庫

Java通過_id查詢mongodb資料庫

本文以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 } } }