測試JDK:1.8
測試系統:WIN10
部分轉載於:http://www.runoob.com/mongodb/mongodb-operators.html 的筆記
MongoClient mongoClient = new MongoClient();
MongoDatabase mongoDatabase = mongoClient.getDatabase("數據庫名");
MongoCollection mongoCollection = mongoDatabase.getCollection("數據庫下的集合");
//-------------------------基本的搜索-----------------------------------
//類似於SQL的"where 搜索的列名 > 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$gt",100));
//類似於SQL的"where 搜索的列名 >= 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$gte",100));
//類似於SQL的"where 搜索的列名 < 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$lt",100));
//類似於SQL的"where 搜索的列名 <= 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$lte",100));
//類似於SQL的"where 搜索的列名 != 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$ne",100));
//類似於SQL的"where 搜索的列名 = 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$eq",100));
//類似於SQL的"where 搜索的列名 > 100 and 搜索的列名 < 100"
Document 搜索條件 = new Document("搜索的列名",new Document("$gt",100)).append("搜索的列名",new Document("$lt",100));
//-------------------------基本的搜索-----------------------------------
//-------------------------較高級的搜索-----------------------------------
//類似於SQL的"where 搜索的列名 like '%搜索的內容%'"
//本人較爲討厭正則表達式,所以這裏沒寫那麼多,喜歡正則表達式的可以去學習一下,菜鳥教程還不錯
Pattern pattern = Pattern.compile("搜索的內容", Pattern.CASE_INSENSITIVE);
Document 搜索條件 = new Document("搜索的列名", pattern);
//類似於SQL的"where 搜索的列名 in ('搜索的內容1','搜索的內容2','搜索的內容3')"
List<String> list = new ArrayList<>();
list.add("搜索的內容1");
list.add("搜索的內容2");
list.add("搜索的內容3");
Document 搜索條件 = new Document("搜索的列名",new Document("$in",list));
//-------------------------較高級的搜索-----------------------------------
MongoIterable<Document> mongoIterable = mongoCollection.find(搜索條件);