如何使用Java将文档插入MongoDB集合?
您可以使用**insert()**方法将文档插入MongoDB现有集合中。
语法
db.coll.insert(doc)
其中:
**db** 是数据库。
**coll** 是您要插入文档的集合(名称)。
**doc** 是您要插入的文档。
示例
> use myDatabase()
switched to db myDatabase()
> db.createCollection(sample)
{ "ok" : 1 }
> db.sample.insert({name:"Ram", age:26, city:"Hyderabad"})
WriteResult({ "nInserted" : 1 })使用Java程序
在Java中,您可以使用**com.mongodb.client.MongoCollection**接口的**insertOne()**方法将文档插入集合。此方法接受一个文档(对象)作为参数,该文档表示您要插入的文档。
因此,要使用Java程序在MongoDB中创建集合:
确保您已在系统中安装MongoDB。
将以下依赖项添加到Java项目的pom.xml文件中。
示例
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency>
通过实例化MongoClient类来创建MongoDB客户端。
使用**getDatabase()**方法连接到数据库。
准备要插入的文档。
使用**getCollection()**方法获取要将文档插入到的集合的对象。
通过将文档(如上创建)作为参数调用insertOne()方法。
示例
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
public static void main( String args[] ) {
//Creating a MongoDB client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Connecting to the database
MongoDatabase database = mongo.getDatabase("myDatabase");
//Creating a collection
database.createCollection("students");
//Preparing a document
Document document = new Document();
document.append("name", "Ram");
document.append("age", 26);
document.append("city", "Hyderabad");
//Inserting the document into the collection
database.getCollection("students").insertOne(document);
System.out.println("Document inserted successfully");
}
}输出
Document inserted successfully
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP