In this tutorial, we are going to discuss database connectivity between Java application and MongoDB. MongoDB is a document based database that is used to store data into JSON format rather than table or relation. It is completely different from the relational database like: mysql. You can get idea of MondoDB from our latest tutorial here MongoDB Tutorial.
在本教程中,我们将讨论Java应用程序与MongoDB之间的数据库连接。 MongoDB是基于文档的数据库,用于将数据存储为JSON格式而不是表或关系。 它与关系数据库(如mysql)完全不同。 您可以在MongoDB教程的最新教程中了解MondoDB。
Now lets start to learn the connectivity process. Before Starting make sure you have mongoDB installed in your computer system. These are some prerequisites that should be followed to get connected.
现在开始学习连接过程。 在开始之前,请确保您已在计算机系统中安装了mongoDB。 这些是连接时必须遵循的一些先决条件。
先决条件 (Prerequisites)
A running MongoDB on localhost using the default port for MongoDB 27017. See Installation Mongodb installation steps.
使用默认端口的MongoDB 27017在localhost上运行的MongoDB。请参阅安装Mongodb安装步骤。
MongoDB Driver.
MongoDB驱动程序。
After installing MongoDB, it is important to have mongodb driver as well. So to get these, you can either visit the official site MongoDB Java Driver or download the Jar file from our site. Keep this JAR file into your java application directory.
安装MongoDB之后,同样重要的是要有mongodb驱动程序。 因此,要获取这些文件,您可以访问官方网站MongoDB Java Driver或从我们的网站下载Jar文件。 将此JAR文件保存在Java应用程序目录中。
Note: We don’t need to use JDBC API for mongodb connectivity, It’s API is completely independent and does not require any other external library.
注意:我们不需要将JDBC API用于mongodb连接,它的API是完全独立的,不需要任何其他外部库。
Following are the essential connectivity steps for Java application to mongodb database.
以下是Java应用程序与mongodb数据库的基本连接步骤。
创建MongoDB实例 (Create MongoDB Instance)
You can instantiate a MongoClient object without any parameters to connect to a MongoDB instance running on localhost on port:27017. Use the following code.
您可以实例化一个没有任何参数的MongoClient对象,以连接到端口27017上在本地主机上运行的MongoDB实例。 使用以下代码。
MongoClient mongoClient = MongoClients.create();You can specify the mongodb host and running port, in case mongodb is running on different port.
如果mongodb在其他端口上运行,则可以指定mongodb主机和运行端口。
MongoClient mongoClient = MongoClients.create("mongodb://hostOne:27017");访问数据库 (Access a Database)
After creating mongoDB instance, use its getDatabase() method to access a database by specifying the name of the database to the getDatabase() method. If a database does not exist, MongoDB creates the database when you first store data for that database. For example, we are connecting to studytonight database.
创建MongoDB实例后,使用其getDatabase()方法通过指定数据库的名称来访问数据库getDatabase()方法。 如果数据库不存在,则在您第一次为该数据库存储数据时,MongoDB会创建该数据库。 例如,我们正在连接到studytonight数据库。
MongoDatabase database = mongoClient.getDatabase("studytonight");访问收藏集 (Access a Collection)
After creating mongoDB database, use its getCollection() method to access a collection by specifying name. If a collection does not exist, MongoDB creates the collection when you first store data for that collection.
创建mongoDB数据库后,使用其getCollection()方法通过指定名称来访问集合。 如果不存在集合,则在您第一次为该集合存储数据时,MongoDB会创建该集合。
Use the following code to create collection, for example : student.
使用以下代码创建集合,例如: student 。
MongoCollection<Document> collection = database.getCollection("student");建立文件 (Create a Document)
To create the document using the Java driver, use the Document class, and use its append() method to include additional fields and values to the document object. For example, see the following code.
要使用Java驱动程序创建文档,请使用Document类,并使用其append()方法将附加字段和值包括到文档对象中。 例如,请参见以下代码。
Document doc = new Document("name", "Ramesh");
doc.append("id",12);插入文件 (Insert a Document)
After creating document, you can insert documents into the collection. We can insert single and multiple documents too. To insert a single document into the collection, you can use the collection’s insertOne() method.
创建文档后,您可以将文档插入集合中。 我们也可以插入单个和多个文档。 要将单个文档插入到集合中,可以使用集合的insertOne()方法。
collection.insertOne(doc);To add multipledocuments, you can use the collection’s insertMany() method which takes a list of documents to insert.
要添加多个文档,可以使用集合的insertMany()方法,该方法获取要插入的文档列表。
提取文件 (Fetch A Document)
You can use the collection's find() method to fetch a record from the document. The find() method returns an iterable so you loop through to get individual data.
您可以使用集合的find()方法从文档中获取记录。 find()方法返回一个可迭代的,因此您可以循环遍历以获取单个数据。
Now Lets put all these steps into one Java application and connect to the MongoDB database.
现在,让我们将所有这些步骤放入一个Java应用程序中,并连接到MongoDB数据库。
Java MongoDB示例: (Java MongoDB Example: )
Here we are connecting to mongodb by specifying the host and port number and then create a database and a collection to store the data. The insertOne() method is used to insert a single record to the document. See the below example.
在这里,我们通过指定主机和端口号连接到mongodb,然后创建一个数据库和一个集合来存储数据。 insertOne()方法用于将单个记录插入文档中。 请参见以下示例。
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class Demo {
public static void main(String[] args){
try{
// Connecting To MongoDB
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Creating DataBase
MongoDatabase db = mongoClient.getDatabase("studytonight");
// Creating Collection/Table
MongoCollection<Document> table = db.getCollection("student");
// Creating Document/Record
Document doc = new Document("name", "Ramesh");
doc.append("id",12);
// Inserting Data
table.insertOne(doc);
}catch(Exception e){
System.out.println(e);
}
}
}从MongoDB访问数据 (Accessing Data from MongoDB)
After creating database and inserting data, now lets fetch that record. We are using find() method to get records from the document and then iterating the record, and displaying by using their names. See the below example.
创建数据库并插入数据之后,现在让我们获取该记录。 我们正在使用find()方法从文档中获取记录,然后对记录进行迭代,并使用它们的名称进行显示。 请参见以下示例。
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class Demo {
public static void main(String[] args){
try{
// Connecting To MongoDB
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Creating DataBase
MongoDatabase db = mongoClient.getDatabase("studytonight");
// Creating Collection/Table
MongoCollection<Document> table = db.getCollection("student");
// Accessing Data
FindIterable<Document> data = table.find();
// Traversing Data
for(Document record : data) {
System.out.println(record.getInteger("id")+" : "+record.getString("name"));
}
mongoClient.close();
}catch(Exception e){
System.out.println(e);
}
}
}12 : Ramesh
12:拉梅什
以JSON格式访问 (Access in JSON Format)
MongoDB is a document based database and used JSON like format to store the data into documents. It provides a method toJSON() to access data into JSON format that we used in this example.
MongoDB是一个基于文档的数据库,并使用类似JSON的格式将数据存储到文档中。 它提供了toJSON()方法,用于将数据访问为本示例中使用的JSON格式。
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class Demo {
public static void main(String[] args){
try{
// Connecting To MongoDB
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Creating DataBase
MongoDatabase db = mongoClient.getDatabase("studytonight");
// Creating Collection/Table
MongoCollection<Document> table = db.getCollection("student");
// Accessing Data
FindIterable<Document> data = table.find();
// Traversing Data
for(Document record : data) {
System.out.println(record.toJson());
}
mongoClient.close();
}catch(Exception e){
System.out.println(e);
}
}
}{"_id": {"$oid": "5ece65f5e8aa304abbf99953"}, "name": "Ramesh", "id": 12}
{“ _id”:{“ $ oid”:“ 5ece65f5e8aa304abbf99953”},“ name”:“ Ramesh”,“ id”:12}
翻译自: https://www.studytonight.com/java/connecting-to-mongodb.php