原文: https://howtodoinjava.com/mongodb/mongodb-find-documents/

学习MongoDB 中找到文档。 此 mongodb 查找文档教程涵盖了多种方法,它们与我们在 SQL 中使用WHERE子句的条件相同,可以查询单个文档查找多个文档

  1. Table of Contents
  2. 1) Select all documents from a collection
  3. 2) Select first document from a collection
  4. 3) Select single document and limited field(s) from a collection
  5. 4) Select all documents with unique id from a collection
  6. 5) Document ids IN clause example
  7. 6) Document ids less than or greater than clause example
  8. 7) Document ids NOT IN clause example
  9. 8) Documents matching multiple fields example
  10. 9) Documents matching field value to some REGEX example

MongoDB 查找文档 – 测试数据准备

为了构建和运行本教程中使用的示例,我在数据库中填充了 20 个员工文档,其中employeeId从 1 到 20,以及employeeNameTestEmployee_1TestEmployee_10

  1. private static void setUpTestData(DBCollection collection){
  2. for (int i=1; i <= 10; i++) {
  3. collection.insert(new BasicDBObject().append("employeeId", i).append("employeeName", "TestEmployee_"+i));
  4. }
  5. }

现在运行我们的示例,并获取不同场景下的数据。

1. MongoDB find() – 从集合中选择所有文档

  1. private static void selectAllRecordsFromACollection(DBCollection collection)
  2. {
  3. DBCursor cursor = collection.find();
  4. while(cursor.hasNext())
  5. {
  6. System.out.println(cursor.next());
  7. }
  8. }

程序输出。

  1. { "_id" : { "$oid" : "538782753641d31b0cad0142"} , "employeeId" : 1 , "employeeName" : "TestEmployee_1"}
  2. { "_id" : { "$oid" : "538782753641d31b0cad0143"} , "employeeId" : 2 , "employeeName" : "TestEmployee_2"}
  3. { "_id" : { "$oid" : "538782753641d31b0cad0144"} , "employeeId" : 3 , "employeeName" : "TestEmployee_3"}
  4. { "_id" : { "$oid" : "538782753641d31b0cad0145"} , "employeeId" : 4 , "employeeName" : "TestEmployee_4"}
  5. { "_id" : { "$oid" : "538782753641d31b0cad0146"} , "employeeId" : 5 , "employeeName" : "TestEmployee_5"}
  6. { "_id" : { "$oid" : "538782753641d31b0cad0147"} , "employeeId" : 6 , "employeeName" : "TestEmployee_6"}
  7. { "_id" : { "$oid" : "538782753641d31b0cad0148"} , "employeeId" : 7 , "employeeName" : "TestEmployee_7"}
  8. { "_id" : { "$oid" : "538782753641d31b0cad0149"} , "employeeId" : 8 , "employeeName" : "TestEmployee_8"}
  9. { "_id" : { "$oid" : "538782753641d31b0cad014a"} , "employeeId" : 9 , "employeeName" : "TestEmployee_9"}
  10. { "_id" : { "$oid" : "538782753641d31b0cad014b"} , "employeeId" : 10 , "employeeName" : "TestEmployee_10"}

2. MongoDB findOne() – 从集合中选择第一个文档

  1. private static void selectFirstRecordInCollection(DBCollection collection)
  2. {
  3. DBObject dbObject = collection.findOne();
  4. System.out.println(dbObject);
  5. }

程序输出:

  1. { "_id" : { "$oid" : "538782a53641ed9125df86c0"} , "employeeId" : 1 , "employeeName" : "TestEmployee_1"}

3. MongoDB where子句 – 从集合中选择单个文档和有限的字段

  1. private static void selectSingleRecordAndFieldByRecordNumber(DBCollection collection)
  2. {
  3. BasicDBObject whereQuery = new BasicDBObject();
  4. whereQuery.put("employeeId", 5);
  5. BasicDBObject fields = new BasicDBObject();
  6. fields.put("employeeId", 1);
  7. DBCursor cursor = collection.find(whereQuery, fields);
  8. while (cursor.hasNext()) {
  9. System.out.println(cursor.next());
  10. }
  11. }

程序输出:

  1. { "_id" : { "$oid" : "53878332364101041fb2c141"} , "employeeId" : 5}

4. MongoDB 通过 ID 查找文档

  1. private static void selectAllRecordByRecordNumber(DBCollection collection)
  2. {
  3. BasicDBObject whereQuery = new BasicDBObject();
  4. whereQuery.put("employeeId", 5);
  5. DBCursor cursor = collection.find(whereQuery);
  6. while(cursor.hasNext()) {
  7. System.out.println(cursor.next());
  8. }
  9. }

程序输出:

  1. { "_id" : { "$oid" : "538783623641e9b2da299fa7"} , "employeeId" : 5 , "employeeName" : "TestEmployee_5"}

5. MongoDB IN子句示例

  1. private static void in_Example(DBCollection collection)
  2. {
  3. BasicDBObject inQuery = new BasicDBObject();
  4. List<Integer> list = new ArrayList<Integer>();
  5. list.add(2);
  6. list.add(4);
  7. list.add(5);
  8. inQuery.put("employeeId", new BasicDBObject("$in", list));
  9. DBCursor cursor = collection.find(inQuery);
  10. while(cursor.hasNext()) {
  11. System.out.println(cursor.next());
  12. }
  13. }

程序输出:

  1. { "_id" : { "$oid" : "5387838d3641024de174c795"} , "employeeId" : 2 , "employeeName" : "TestEmployee_2"}
  2. { "_id" : { "$oid" : "5387838d3641024de174c797"} , "employeeId" : 4 , "employeeName" : "TestEmployee_4"}
  3. { "_id" : { "$oid" : "5387838d3641024de174c798"} , "employeeId" : 5 , "employeeName" : "TestEmployee_5"}

6. MongoDB 小于或大于子句示例

  1. private static void lessThan_GreaterThan_Example(DBCollection collection)
  2. {
  3. BasicDBObject getQuery = new BasicDBObject();
  4. getQuery.put("employeeId", new BasicDBObject("$gt", 2).append("$lt", 5));
  5. DBCursor cursor = collection.find(getQuery);
  6. while(cursor.hasNext()) {
  7. System.out.println(cursor.next());
  8. }
  9. }

程序输出:

  1. { "_id" : { "$oid" : "538783b63641720cd34f98c8"} , "employeeId" : 3 , "employeeName" : "TestEmployee_3"}
  2. { "_id" : { "$oid" : "538783b63641720cd34f98c9"} , "employeeId" : 4 , "employeeName" : "TestEmployee_4"}

7. MongoDb NOT IN子句示例

  1. private static void negation_Example(DBCollection collection)
  2. {
  3. BasicDBObject neQuery = new BasicDBObject();
  4. neQuery.put("employeeId", new BasicDBObject("$ne", 4));
  5. DBCursor cursor = collection.find(neQuery);
  6. while(cursor.hasNext()) {
  7. System.out.println(cursor.next());
  8. }
  9. }

程序输出:

  1. { "_id" : { "$oid" : "538783db3641d3ca9d400510"} , "employeeId" : 1 , "employeeName" : "TestEmployee_1"}
  2. { "_id" : { "$oid" : "538783db3641d3ca9d400511"} , "employeeId" : 2 , "employeeName" : "TestEmployee_2"}
  3. { "_id" : { "$oid" : "538783db3641d3ca9d400512"} , "employeeId" : 3 , "employeeName" : "TestEmployee_3"}
  4. { "_id" : { "$oid" : "538783db3641d3ca9d400514"} , "employeeId" : 5 , "employeeName" : "TestEmployee_5"} //4 is missing
  5. { "_id" : { "$oid" : "538783db3641d3ca9d400515"} , "employeeId" : 6 , "employeeName" : "TestEmployee_6"}
  6. { "_id" : { "$oid" : "538783db3641d3ca9d400516"} , "employeeId" : 7 , "employeeName" : "TestEmployee_7"}
  7. { "_id" : { "$oid" : "538783db3641d3ca9d400517"} , "employeeId" : 8 , "employeeName" : "TestEmployee_8"}
  8. { "_id" : { "$oid" : "538783db3641d3ca9d400518"} , "employeeId" : 9 , "employeeName" : "TestEmployee_9"}
  9. { "_id" : { "$oid" : "538783db3641d3ca9d400519"} , "employeeId" : 10 , "employeeName" : "TestEmployee_10"}

8. MongoDB 查找匹配多个字段的文档示例

  1. private static void andLogicalComparison_Example(DBCollection collection)
  2. {
  3. BasicDBObject andQuery = new BasicDBObject();
  4. List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
  5. obj.add(new BasicDBObject("employeeId", 2));
  6. obj.add(new BasicDBObject("employeeName", "TestEmployee_2"));
  7. andQuery.put("$and", obj);
  8. System.out.println(andQuery.toString());
  9. DBCursor cursor = collection.find(andQuery);
  10. while (cursor.hasNext()) {
  11. System.out.println(cursor.next());
  12. }
  13. }

程序输出:

  1. { "$and" : [ { "employeeId" : 2} , { "employeeName" : "TestEmployee_2"}]}
  2. { "_id" : { "$oid" : "5387840336418a41167caaa4"} , "employeeId" : 2 , "employeeName" : "TestEmployee_2"}

9. MongoDb 查找匹配REGEX的文档示例

  1. private static void regex_Example(DBCollection collection) {
  2. BasicDBObject regexQuery = new BasicDBObject();
  3. regexQuery.put("employeeName",
  4. new BasicDBObject("$regex", "TestEmployee_[3]")
  5. .append("$options", "i"));
  6. System.out.println(regexQuery.toString());
  7. DBCursor cursor = collection.find(regexQuery);
  8. while (cursor.hasNext()) {
  9. System.out.println(cursor.next());
  10. }
  11. }

程序输出:

  1. { "employeeName" : { "$regex" : "TestEmployee_[3]" , "$options" : "i"}}
  2. { "_id" : { "$oid" : "538784213641917ce7068c57"} , "employeeId" : 3 , "employeeName" : "TestEmployee_3"}

10. 所有 mondodb 查找查询示例

  1. package examples.mongodb.crud;
  2. import java.net.UnknownHostException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import com.mongodb.BasicDBObject;
  6. import com.mongodb.DB;
  7. import com.mongodb.DBCollection;
  8. import com.mongodb.DBCursor;
  9. import com.mongodb.DBObject;
  10. import com.mongodb.MongoClient;
  11. import com.mongodb.WriteResult;
  12. public class MongoDBSelectExample {
  13. private static void setUpTestData(DBCollection collection){
  14. for (int i=1; i <= 10; i++) {
  15. collection.insert(new BasicDBObject().append("employeeId", i).append("employeeName", "TestEmployee_"+i));
  16. }
  17. }
  18. public static void main(String[] args) throws UnknownHostException
  19. {
  20. MongoClient mongo = new MongoClient("localhost", 27017);
  21. DB db = mongo.getDB("howtodoinjava");
  22. DBCollection collection = db.getCollection("users");
  23. //Delete All documents before running example again
  24. WriteResult result = collection.remove(new BasicDBObject());
  25. System.out.println(result.toString());
  26. //Set up test data
  27. setUpTestData(collection);
  28. //Select all document from a collection
  29. selectAllRecordsFromACollection(collection);
  30. //Select first document in collection
  31. selectFirstRecordInCollection(collection);
  32. //Select single document and single field based on record number
  33. selectSingleRecordAndFieldByRecordNumber(collection);
  34. //Select all documents where record number = n
  35. selectAllRecordByRecordNumber(collection);
  36. //In example
  37. in_Example(collection);
  38. //Less than OR greater than example
  39. lessThan_GreaterThan_Example(collection);
  40. //Select document where record number != n
  41. negation_Example(collection);
  42. //And logical comparison query example
  43. andLogicalComparison_Example(collection);
  44. //Select documents based on regex match LIKE example
  45. regex_Example(collection);
  46. }
  47. private static void selectFirstRecordInCollection(DBCollection collection) {
  48. DBObject dbObject = collection.findOne();
  49. System.out.println(dbObject);
  50. }
  51. private static void selectAllRecordsFromACollection(DBCollection collection) {
  52. DBCursor cursor = collection.find();
  53. while(cursor.hasNext()) {
  54. System.out.println(cursor.next());
  55. }
  56. }
  57. private static void selectSingleRecordAndFieldByRecordNumber(DBCollection collection) {
  58. BasicDBObject whereQuery = new BasicDBObject();
  59. whereQuery.put("employeeId", 5);
  60. BasicDBObject fields = new BasicDBObject();
  61. fields.put("employeeId", 1);
  62. DBCursor cursor = collection.find(whereQuery, fields);
  63. while (cursor.hasNext()) {
  64. System.out.println(cursor.next());
  65. }
  66. }
  67. private static void selectAllRecordByRecordNumber(DBCollection collection) {
  68. BasicDBObject whereQuery = new BasicDBObject();
  69. whereQuery.put("employeeId", 5);
  70. DBCursor cursor = collection.find(whereQuery);
  71. while(cursor.hasNext()) {
  72. System.out.println(cursor.next());
  73. }
  74. }
  75. private static void in_Example(DBCollection collection) {
  76. BasicDBObject inQuery = new BasicDBObject();
  77. List<Integer> list = new ArrayList<Integer>();
  78. list.add(2);
  79. list.add(4);
  80. list.add(5);
  81. inQuery.put("employeeId", new BasicDBObject("$in", list));
  82. DBCursor cursor = collection.find(inQuery);
  83. while(cursor.hasNext()) {
  84. System.out.println(cursor.next());
  85. }
  86. }
  87. private static void lessThan_GreaterThan_Example(
  88. DBCollection collection) {
  89. BasicDBObject gtQuery = new BasicDBObject();
  90. gtQuery.put("employeeId", new BasicDBObject("$gt", 2).append("$lt", 5));
  91. DBCursor cursor = collection.find(gtQuery);
  92. while(cursor.hasNext()) {
  93. System.out.println(cursor.next());
  94. }
  95. }
  96. private static void negation_Example(DBCollection collection) {
  97. BasicDBObject neQuery = new BasicDBObject();
  98. neQuery.put("employeeId", new BasicDBObject("$ne", 4));
  99. DBCursor cursor = collection.find(neQuery);
  100. while(cursor.hasNext()) {
  101. System.out.println(cursor.next());
  102. }
  103. }
  104. private static void andLogicalComparison_Example(DBCollection collection) {
  105. BasicDBObject andQuery = new BasicDBObject();
  106. List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
  107. obj.add(new BasicDBObject("employeeId", 2));
  108. obj.add(new BasicDBObject("employeeName", "TestEmployee_2"));
  109. andQuery.put("$and", obj);
  110. System.out.println(andQuery.toString());
  111. DBCursor cursor = collection.find(andQuery);
  112. while (cursor.hasNext()) {
  113. System.out.println(cursor.next());
  114. }
  115. }
  116. private static void regex_Example(DBCollection collection) {
  117. BasicDBObject regexQuery = new BasicDBObject();
  118. regexQuery.put("employeeName",
  119. new BasicDBObject("$regex", "TestEmployee_[3]")
  120. .append("$options", "i"));
  121. System.out.println(regexQuery.toString());
  122. DBCursor cursor = collection.find(regexQuery);
  123. while (cursor.hasNext()) {
  124. System.out.println(cursor.next());
  125. }
  126. }
  127. }

所有这些都是通过从 MongoDB 中获取文件的不同技术。

学习愉快!

参考文献:

MongoDB find()文档