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