- MongoDB 教程
- MongoDB - 首页
- MongoDB - 概述
- MongoDB - 优势
- MongoDB - 环境搭建
- MongoDB - 数据建模
- MongoDB - 创建数据库
- MongoDB - 删除数据库
- MongoDB - 创建集合
- MongoDB - 删除集合
- MongoDB - 数据类型
- MongoDB - 插入文档
- MongoDB - 查询文档
- MongoDB - 更新文档
- MongoDB - 删除文档
- MongoDB - 投影
- MongoDB - 限制记录
- MongoDB - 排序记录
- MongoDB - 索引
- MongoDB - 聚合
- MongoDB - 复制
- MongoDB - 分片
- MongoDB - 创建备份
- MongoDB - 部署
- MongoDB - Java
- MongoDB - PHP
- 高级 MongoDB
- MongoDB - 关系
- MongoDB - 数据库引用
- MongoDB - 覆盖查询
- MongoDB - 分析查询
- MongoDB - 原子操作
- MongoDB - 高级索引
- MongoDB - 索引限制
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - 文本搜索
- MongoDB - 正则表达式
- 使用 Rockmongo
- MongoDB - GridFS
- MongoDB - 有盖集合
- 自动递增序列
- MongoDB 有用资源
- MongoDB - 问答
- MongoDB - 快速指南
- MongoDB - 有用资源
- MongoDB - 讨论
MongoDB - Java
在本节中,我们将学习如何设置 MongoDB 客户端。
安装
在您的 Java 程序中开始使用 MongoDB 之前,您需要确保机器上已安装 MongoDB 客户端和 Java。您可以查看 Java 教程,了解如何在您的机器上安装 Java。现在,让我们检查如何设置 MongoDB 客户端。
您需要下载 jar 文件 **mongodb-driver-3.11.2.jar 及其依赖项 mongodb-driver-core-3.11.2.jar**。请确保下载这些 jar 文件的最新版本。
您需要将下载的 jar 文件包含到您的类路径中。
连接到数据库
要连接数据库,您需要指定数据库名称,如果数据库不存在,MongoDB 会自动创建它。
以下是连接到数据库的代码片段:
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ConnectToDB {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Credentials ::"+ credential);
}
}
现在,让我们编译并运行上述程序来创建我们的数据库 myDb,如下所示。
$javac ConnectToDB.java $java ConnectToDB
执行后,上述程序会给出以下输出。
Connected to the database successfully
Credentials ::MongoCredential{
mechanism = null,
userName = 'sampleUser',
source = 'myDb',
password = <hidden>,
mechanismProperties = {}
}
创建集合
要创建集合,使用 **com.mongodb.client.MongoDatabase** 类的 **createCollection()** 方法。
以下是创建集合的代码片段:
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
//Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully Collection created successfully
获取/选择集合
要从数据库中获取/选择集合,使用 **com.mongodb.client.MongoDatabase** 类的 **getCollection()** 方法。
以下是获取/选择集合的程序:
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class selectingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Creating a collection
System.out.println("Collection created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("myCollection");
System.out.println("Collection myCollection selected successfully");
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully Collection created successfully Collection myCollection selected successfully
插入文档
要将文档插入 MongoDB,使用 **com.mongodb.client.MongoCollection** 类的 **insert()** 方法。
以下是插入文档的代码片段:
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
Document document = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "https://tutorialspoint.com/mongodb/")
.append("by", "tutorials point");
//Inserting document into the collection
collection.insertOne(document);
System.out.println("Document inserted successfully");
}
编译后,上述程序会给出以下结果:
Connected to the database successfully Collection sampleCollection selected successfully Document inserted successfully
检索所有文档
要从集合中选择所有文档,使用 **com.mongodb.client.MongoCollection** 类的 **find()** 方法。此方法返回一个游标,因此您需要迭代此游标。
以下是选择所有文档的程序:
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class RetrievingAllDocuments {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
Document document1 = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "https://tutorialspoint.com/mongodb/")
.append("by", "tutorials point");
Document document2 = new Document("title", "RethinkDB")
.append("description", "database")
.append("likes", 200)
.append("url", "https://tutorialspoint.com/rethinkdb/")
.append("by", "tutorials point");
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
collection.insertMany(list);
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully
Collection sampleCollection selected successfully
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=https://tutorialspoint.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=https://tutorialspoint.com/rethinkdb/, by=tutorials point}}
更新文档
要更新集合中的文档,使用 **com.mongodb.client.MongoCollection** 类的 **updateOne()** 方法。
以下是选择第一个文档的程序:
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class UpdatingDocuments {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection myCollection selected successfully");
collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));
System.out.println("Document update successfully...");
// Retrieving the documents after updation
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully
Collection myCollection selected successfully
Document update successfully...
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=https://tutorialspoint.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=https://tutorialspoint.com/rethinkdb/, by=tutorials point}}
删除文档
要从集合中删除文档,您需要使用 **com.mongodb.client.MongoCollection** 类的 **deleteOne()** 方法。
以下是删除文档的程序:
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DeletingDocuments {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
// Deleting the documents
collection.deleteOne(Filters.eq("title", "MongoDB"));
System.out.println("Document deleted successfully...");
// Retrieving the documents after updation
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully
Collection sampleCollection selected successfully
Document deleted successfully...
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=https://tutorialspoint.com/rethinkdb/, by=tutorials point}}
删除集合
要从数据库中删除集合,您需要使用 **com.mongodb.client.MongoCollection** 类的 **drop()** 方法。
以下是删除集合的程序:
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DropingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Creating a collection
System.out.println("Collections created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// Dropping a Collection
collection.drop();
System.out.println("Collection dropped successfully");
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully Collection sampleCollection selected successfully Collection dropped successfully
列出所有集合
要列出数据库中的所有集合,您需要使用 **com.mongodb.client.MongoDatabase** 类的 **listCollectionNames()** 方法。
以下是列出数据库所有集合的程序:
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ListOfCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Collection created successfully");
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
}
}
编译后,上述程序会给出以下结果:
Connected to the database successfully Collection created successfully myCollection myCollection1 myCollection5
其余 MongoDB 方法 **save()、limit()、skip()、sort()** 等的工作方式与后续教程中解释的相同。