Java 与 MongoDB - 选择文档



要选择集合中的文档,可以使用 collection.find()collection.find(filter) 方法选择集合的文档。

// find all documents of a collection
collection.find();

// find document(s) fulfiling the filter criteria
collection.find(filter);

示例

以下是显示所选文档的代码段 -

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://127.0.0.1:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find all documents
      FindIterable<Document> allDocuments = collection.find();

      for (Document document : allDocuments) {
         System.out.println(document);
      }
      System.out.println("***Selected Document***");
      
      // Select a particular document
      FindIterable<Document> documents = collection.find(Filters.eq("First_Name","Mahesh"));
      for (Document document : documents) {
         System.out.println(document);
      }
   }
}

现在,让我们像下面所示编译并运行上述程序。

$javac Tester.java 
$java Tester

输出

执行后,上述程序会给你以下输出。

Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, [email protected], phone=9034343345}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, [email protected], phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}}
********
Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, [email protected], phone=9034343345}}
广告