Java Mongodb 简明教程
Java & MongoDB - Overview
MongoDB 开发者团队提供了适用于 Java 的 MongoDB 驱动程序,并为此准备了各种资源。
MongoDB developer team has provided MongoDB Driver for Java and have various resources available for it.
使用 Java 连接到 MongoDB 的第一步是,将 mongodb 驱动程序放入 Java 类路径,然后使用 mongodb API 连接到数据库。
First step in connecting to MongoDB using Java is to have mongodb driver in the java classpath and then use mongodb API to connect to the database.
Connecting to MongoDB database
假设已在本机安装 MongoDB,并且使用的是默认端口,则可以使用以下语法连接到 MongoDB 数据库。
Suppose, MongoDB is installed locally and using default port then following syntax connects to MongoDB database.
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
因为 MongoClient 采用了各种默认设置,因此也可以按照以下方式使用它。
As MongoClient assumes various default, it can be used using the following way as well.
MongoClient mongoClient = MongoClients.create();
Creating/Connecting to Database
实例化 mongoClient 后,可以使用其 getDatabase() 方法获取与数据库的连接。
Once mongoClient is instantiated, its getDatabase() method can be used to get connection to a database.
MongoDatabase database = mongoClient.getDatabase("myDb");
如果数据库不存在,则上述命令会创建数据库。
In case database is not present then above command will create the same.
后续章节中,我们将使用 Java 演示基于 MongoDB 的各种操作。
In subsequent chapters, we’ll see the various operations on MongoDB using Java.
Java & MongoDB - Environment Setup
Install MongoDB database
按照 MongoDB - Environment 中的说明进行 MongoDB 安装
Follow the MongoDB installation steps using MongoDB - Environment
Install Java
可以免费从以下链接下载 Java SE −
Java SE can be downloaded for free from the following link −
你可以根据自己的操作系统下载一个版本。
You download a version based on your operating system.
按照说明下载 Java,并运行 .exe 在你的计算机上安装 Java。在计算机上安装 Java 后,你需要设置环境变量来指向正确的安装目录。
Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Setting Up the Path for Windows 2000/XP
假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中 −
Assuming you have installed Java in c:\Program Files\java\jdk directory −
-
Right-click on 'My Computer' and select 'Properties'.
-
Click on the 'Environment variables' button under the 'Advanced' tab.
-
Now, alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting Up the Path for Windows 95/98/ME
假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中 −
Assuming you have installed Java in c:\Program Files\java\jdk directory −
-
Edit the 'C:\autoexec.bat' file and add the following line at the end − SET PATH=%PATH%;C:\Program Files\java\jdk\bin
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
环境变量 PATH 应设置为指向已安装 Java 二进制文件的位置。如果你在这方面遇到问题,请参阅 shell 文档。
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
例如,如果你使用 bash 作为 shell,则需要在“‘.bashrc: export PATH=/path/to/java:$PATH’”的末尾添加以下行
For example, if you use bash as your shell, then you would add the following line at the end of your '.bashrc: export PATH=/path/to/java:$PATH'
Popular Java Editors
要编写 Java 程序,你需要一个文本编辑器。市场上有更复杂的 IDE 可用。但目前,你可以考虑以下选项之一:
To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following −
-
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or TextPad.
-
Netbeans − It is a Java IDE that is open-source and free. It can be downloaded from https://netbeans.org/index.html.
-
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/.
Java MongoDB Driver
-
You need to download the jar mongo-java-driver.jar. Make sure to download the latest release of these jar files.
-
You need to include the downloaded jar files into your classpath.
-
We are using mongo-java-driver-3.12.8.jar to run examples.
Java & MongoDB - Connecting Database
要连接数据库,你需要指定数据库名称;如果数据库不存在,则 MongoDB 会自动创建它。
To connect database, you need to specify the database name, if the database doesn’t exist then MongoDB creates it automatically.
MongoDatabase database = mongo.getDatabase("myDb");
Example
以下是连接数据库的代码片段:
Following is the code snippet to connect to the database −
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongo.getDatabase("myDb");
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
System.out.println("Credentials ::"+ credential);
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Show Databases
要显示数据库,可以使用 MongoClient.listDatabaseNames() 方法获取所有数据库的名字。
To show databases, you can use MongoClient.listDatabaseNames() method to get the name of all the databases.
MongoIterable<String> list = mongoClient.listDatabaseNames();
for (String name : list) {
System.out.println(name);
}
由于我们在 Connect Database 章节中创建了一个空数据库,我们需要插入一个文档,以便在 MongoDB 数据库列表中显示它。
As we have created an empty database in Connect Database chapter, we need to insert a document to make it visible in mongodb database list.
Example
以下是列出数据库的代码片段 −
Following is the code snippet to list down database −
import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
database.createCollection("sampleCollection");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
Document document = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "http://www.tutorialspoint.com/mongodb/")
.append("by", "tutorials point");
//Inserting document into the collection
collection.insertOne(document);
MongoIterable<String> list = mongoClient.listDatabaseNames();
for (String name : list) {
System.out.println(name);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Drop Database
若要删除数据库,可以使用 MongoDatabse.drop() 方法来删除选定的数据库。
To drop a databases, you can use MongoDatabse.drop() method to drop the selected databases.
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create();
// connect the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// drop the database
database.drop();
Example
以下是删除数据库的代码片段 −
Following is the code snippet to drop a database −
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// drop the database
database.drop();
System.out.println("Database dropped.");
// print the databases
MongoIterable<String> list = mongoClient.listDatabaseNames();
for (String name : list) {
System.out.println(name);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Create Collection
若要删除数据库,可以使用 MongoDatabse.createCollection() 方法在数据库中创建集合。
To drop a databases, you can use MongoDatabse.createCollection() method to create a collection in the databases.
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create();
// Connect the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("sampleCollection");
Example
以下是创建集合的代码片段 −
Following is the code snippet to create a collection −
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// Connect to database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("sampleCollection");
System.out.println("Collection created.");
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Drop Collection
若要删除数据库,可以使用 collection.drop() 方法删除数据库中的集合。
To drop a databases, you can use collection.drop() method to drop a collection in the databases.
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// delete the collection
collection.drop();
Example
以下是删除集合的代码片段 −
Following is the code snippet to drop a collection −
import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// get the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
collection.drop();
System.out.println("Collection dropped.");
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Display Collections
若要显示集合列表,可以使用 database.listCollectionNames() 方法获取数据库中集合名称的列表。
To display list of collections, you can use database.listCollectionNames() method to get the list of collection names in the databases.
MongoIterable<String> collections = database.listCollectionNames();
Example
以下是显示集合列表的代码片段 −
Following is the code snippet to display list of collections −
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// Get the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("sampleCollection");
// Get the list of collection names
MongoIterable<String> collections = database.listCollectionNames();
for (String name : collections) {
System.out.println(name);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Insert Document
要插入一个文档到某个集合中,您可以使用 collection.insertOne() 或 collection.insertMany() 方法将文档插入集合。
To insert a document in a collection, you can use collection.insertOne() or collection.insertMany() methods to insert documents in the collection.
// insert a single document
collection.insertOne(document);
// insert multiple documents
collection.insertMany(documents);
Example
以下是将文档插入集合的代码段 −
Following is the code snippet to insert documents in a collection −
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
Document document = new Document("First_Name", "Mahesh")
.append("Last_Name", "Parashar")
.append("Date_Of_Birth", "1990-08-21")
.append("e_mail", "mahesh_parashar.123@gmail.com")
.append("phone", "9034343345");
collection.insertOne(document);
List<Document> documents = new ArrayList<>();
documents.add(new Document("First_Name", "Radhika")
.append("Last_Name", "Sharma")
.append("Date_Of_Birth", "1995-09-26")
.append("e_mail", "radhika_sharma.123@gmail.com")
.append("phone", "9000012345"));
documents.add(new Document("First_Name", "Rachel")
.append("Last_Name", "Christopher")
.append("Date_Of_Birth", "1990-02-16")
.append("e_mail", "Rachel_Christopher.123@gmail.com")
.append("phone", "9000054321"));
documents.add(new Document("First_Name", "Fathima")
.append("Last_Name", "Sheik")
.append("Date_Of_Birth", "1990-02-16")
.append("e_mail", "Fathima_Sheik.123@gmail.com")
.append("phone", "9000054321"));
collection.insertMany(documents);
System.out.println("Documents inserted.");
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Select Document
若要选择一个集合中的文档,可以使用 collection.find() 或 collection.find(filter) 方法选择一个集合的文档。
To select a document in a collection, you can use collection.find() or collection.find(filter) methods to select documents of a collection.
// find all documents of a collection
collection.find();
// find document(s) fulfiling the filter criteria
collection.find(filter);
Example
以下是显示选定文档的代码片段 −
Following is the code snippet to display selected documents −
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://localhost: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);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Output
在执行上述程序时,您将得到以下输出。
On executing, the above program gives you the following output.
Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, e_mail=mahesh_parashar.123@gmail.com, phone=9034343345}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
********
Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, e_mail=mahesh_parashar.123@gmail.com, phone=9034343345}}
Java & MongoDB - Update Document
要更新集合中的一个文档,您可以使用 collection.updateOne() 方法来更新集合中的一个特定文档。
To update a document in a collection, you can use collection.updateOne() method to update a particular document of a collection.
collection.updateOne(filter,update);
Example
以下是用来更新和显示更新后文档的代码段 −
Following is the code snippet to update and display updated document −
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;
import com.mongodb.client.model.Updates;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// Find all documents
collection.updateOne(Filters.eq("First_Name","Mahesh"),
Updates.set("e_mail", "maheshparashar@gmail.com"));
System.out.println("Document Updated.");
System.out.println("***Updated Document***");
// Select a particular document
FindIterable<Document> documents = collection.find(Filters.eq("First_Name","Mahesh"));
for (Document document : documents) {
System.out.println(document);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Java & MongoDB - Delete Document
若要删除一个集合中的文档,可以使用 collection.deleteOne() 方法删除一个集合中的特定文档。
To delete a document in a collection, you can use collection.deleteOne() method to delete a particular document of a collection.
collection.deleteOne(filter);
Example
以下是删除一个文档并显示其余文档的代码片段 −
Following is the code snippet to delete a document and display remaining documents −
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://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// Find all documents
collection.deleteOne(Filters.eq("First_Name","Mahesh"));
System.out.println("Document deleted.");
System.out.println("***Documents***");
// Select a particular document
FindIterable<Document> documents = collection.find();
for (Document document : documents) {
System.out.println(document);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Output
在执行上述程序时,您将得到以下输出。
On executing, the above program gives you the following output.
Document deleted.
***Documents***
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
Java & MongoDB - Embedded Documents
要将包含嵌入式文档的文档插入集合中,您可以使用 DBObject / BasicDBObject 对象,如下所示 −
To insert a document with embedded document in a collection, you can use DBObject/BasicDBObject objects as shown below −
// Create an embedded document
BasicDBObject comment = new BasicDBObject();
comment.put("user", "User1");
comment.put("message", "My First Comment");
comment.put("dateCreated", "20/2/2020");
comment.put("like", "0");
// create an array
List<String> tags = new ArrayList<String>();
tags.add("mongodb");
tags.add("database");
tags.add("NoSQL");
// add array and embedded documents
Document document = new Document("title", "MongoDB Overview")
.append("tags",tags)
.append("comment", comment);
Example
以下是用来插入包含嵌入式文档的文档并对其进行显示的代码段 −
Following is the code snippet to insert a document with embedded documents and display them −
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("post");
MongoCollection<Document> collection = database.getCollection("post");
List<String> tags = new ArrayList<String>();
tags.add("mongodb");
tags.add("database");
tags.add("NoSQL");
BasicDBObject comment1 = new BasicDBObject();
comment1.put("user", "User1");
comment1.put("message", "My First Comment");
comment1.put("dateCreated", "20/2/2020");
comment1.put("like", "0");
BasicDBObject comment2 = new BasicDBObject();
comment2.put("user", "User2");
comment2.put("message", "My Second Comment");
comment2.put("dateCreated", "20/2/2020");
comment2.put("like", "0");
List<DBObject> comments = new ArrayList<DBObject>();
comments.add(comment1);
comments.add(comment2);
Document document = new Document("title", "MongoDB Overview")
.append("description", "MongoDB is no SQL database")
.append("by", "tutorials point")
.append("url", "http://www.tutorialspoint.com")
.append("tags",tags)
.append("comments", comments);
collection.insertOne(document);
FindIterable<Document> documents = collection.find(Filters.eq("title","MongoDB Overview"));
for (Document doc : documents) {
System.out.println(doc);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
在执行上述程序时,您将得到以下输出。
On executing, the above program gives you the following output.
Output
Document{{_id=60b7ab7614bd6b4a14b46d47, title=MongoDB Overview,
description=MongoDB is no SQL database, by=tutorials point,
url=http://www.tutorialspoint.com, tags=[mongodb, database, NoSQL],
comments=[Document{{user=User1, message=My First Comment,
dateCreated=20/2/2020, like=0}}, Document{{user=User2, message=My Second Comment,
dateCreated=20/2/2020, like=0}}]
}}
Java & MongoDB - Referenced Documents
若要插入一个带有引用文档的文档到一个集合中,可以使用 DBRef 对象,如下所示 −
To insert a document with referenced documents in a collection, you can use DBRef object as shown below −
// create a document
Document comment1 = new Document();
comment1.put("_id", "comment1");
comment1.put("user", "User1");
comment1.put("message", "My First Comment");
comment1.put("dateCreated", "20/2/2020");
comment1.put("like", "0");
// create a database reference
DBRef comment1Ref = new DBRef("post", comment1.get("_id"));
// insert the reference in the document
Document document = new Document("title", "Java Overview")
.append("comment1", comment1Ref);
Example
以下是插入一个带有引用文档的文档并显示它们的代码片段 −
Following is the code snippet to insert a document with referenced documents and display them −
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.DBRef;
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://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
MongoCollection<Document> collection = database.getCollection("post");
List<String> tags = new ArrayList<String>();
tags.add("mongodb");
tags.add("database");
tags.add("NoSQL");
Document comment1 = new Document();
comment1.put("_id", "comment1");
comment1.put("user", "User1");
comment1.put("message", "My First Comment");
comment1.put("dateCreated", "20/2/2020");
comment1.put("like", "0");
DBRef comment1Ref = new DBRef("post", comment1.get("_id"));
Document comment2 = new Document();
comment2.put("_id", "comment2");
comment2.put("user", "User2");
comment2.put("message", "My Second Comment");
comment2.put("dateCreated", "20/2/2020");
comment2.put("like", "0");
DBRef comment2Ref = new DBRef("post", comment2.get("_id"));
List<Document> comments = new ArrayList<Document>();
comments.add(comment1);
comments.add(comment2);
Document document = new Document("title", "Java Overview")
.append("description", "Java is programming language")
.append("by", "tutorials point")
.append("url", "http://www.tutorialspoint.com")
.append("tags",tags)
.append("comment1", comment1Ref)
.append("comment2", comment2Ref);
collection.insertMany(comments);
collection.insertOne(document);
FindIterable<Document> documents = collection.find(Filters.eq("title","Java Overview"));
for (Document doc : documents) {
System.out.println(doc);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Output
在执行上述程序时,您将得到以下输出。
On executing, the above program gives you the following output.
Document{{_id=60b7b26b7671f469993fdc3c, title=Java Overview,
description=Java is programming language, by=tutorials point,
url=http://www.tutorialspoint.com, tags=[mongodb, database, NoSQL],
comment1={ "$ref" : "post", "$id" : "comment1" }, comment2={ "$ref" : "post", "$id" : "comment2" }
}}
Java & MongoDB - Limiting Documents
若要选择一个集合中给定数量的文档,可以使用 collection.find().limit() 方法选择所需的文档数。
To select a given number of document in a collection, you can use collection.find().limit() methods to select required no. of documents of a collection.
int n = 2;
// find required documents of a collection
collection.find().limit(n);
Example
以下是显示数量有限的文档的代码片段 −
Following is the code snippet to display limited documents −
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;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// Find two documents
FindIterable<Document> allDocuments = collection.find().limit(2);
for (Document document : allDocuments) {
System.out.println(document);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Output
在执行上述程序时,您将得到以下输出。
On executing, the above program gives you the following output.
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Java & MongoDB - Sorting Documents
若要获取一个集合中已排序的文档,可以使用 collection.find().sort() 方法选择一个集合的已排序文档。
To get sorted document in a collection, you can use collection.find().sort() methods to select sorted documents of a collection.
// find sorted documents of a collection
collection.find().sort(new BasicDBObject("First_Name",-1));
Example
以下是显示已排序文档的代码片段 −
Following is the code snippet to display sorted documents −
import org.bson.Document;
import com.mongodb.BasicDBObject;
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;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("***Discending Order***");
// Sort in Descending order
FindIterable<Document> allDocuments = collection.find().sort(new BasicDBObject("First_Name",-1));
for (Document document : allDocuments) {
System.out.println(document);
}
System.out.println("***Ascending Order***");
// Sort in Ascending order
allDocuments = collection.find().sort(new BasicDBObject("First_Name",1));
for (Document document : allDocuments) {
System.out.println(document);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester
Output
在执行上述程序时,您将得到以下输出。
On executing, the above program gives you the following output.
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
***Ascending Order***
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}