- 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 - 对象 ID
- MongoDB - 映射减少
- MongoDB - 文本搜索
- MongoDB - 正则表达式
- 与 Rockmongo 合作
- MongoDB-GridFS
- MongoDB - 上限集合
- 自动递增序列
- MongoDB 有用资源
- MongoDB - 问题与解答
- MongoDB - 快速指南
- MongoDB - 有用的资源
- MongoDB - 讨论
MongoDB-Java
在本章中,我们将学习如何设置 MongoDB CLIENT。
安装
在开始在 Java 程序中使用 MongoDB 之前,您需要确保计算机上已设置 MongoDB CLIENT 和 Java。您可以查看 Java 教程以了解您计算机上的 Java 安装。现在,让我们看看如何设置 MongoDB CLIENT。
您需要下载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", "http://www.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", "http://www.tutorialspoint.com/mongodb/") .append("by", "tutorials point"); Document document2 = new Document("title", "RethinkDB") .append("description", "database") .append("likes", 200) .append("url", "http://www.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=http://www.tutorialspoint.com/mongodb/, by=tutorials point}} Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.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=http://www.tutorialspoint.com/mongodb/, by=tutorials point}} Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.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=http://www.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()等的工作方式与后续教程中的解释相同。