# Java MongoDB：在集合中插入文档的示例

> 原文： [https://howtodoinjava.com/mongodb/java-mongodb-insert-documents-in-collection-examples/](https://howtodoinjava.com/mongodb/java-mongodb-insert-documents-in-collection-examples/)

在 [**MongoDB 学习系列**](//howtodoinjava.com/category/nosql/mongodb/ "learn mongodb")中，我们已经介绍了 [MongoDB 基础知识](//howtodoinjava.com/nosql/introduction-to-mongodb-why-mongodb/ "Introduction to MongoDB: Why MongoDB?")， [**在 Windows 中安装 MongoDB**](//howtodoinjava.com/nosql/mongodb/how-to-install-mongodb-on-windows/ "How to Install MongoDB on Windows") 和[**如何从集合中查询/选择文档**](//howtodoinjava.com/nosql/mongodb/mongodb-selectqueryfind-documents-examples/ "MongoDB : Select/Query/Find Document(s) Examples")。 在本教程中，我列出了 4 种可用于在 MongoDB 中向集合中插入或添加文档的方法。

```java
List of examples in this tutorial

1) Insert BasicDBObject in collection
2) Use DBObjectBuilder to insert document in collection
3) Use java.util.HashMap to build BasicDBObject and insert into collection
4) Parse JSON to build DBObject and insert into collection
```

## 我们将插入集合的示例文档

```java
{
    "name":"lokesh",
    "website":"howtodoinjava.com",
    "address":{
        "addressLine1":"Some address",
        "addressLine2":"Karol Bagh",
        "addressLine3":"New Delhi, India"
    }
}

```

## 1）在集合中插入`BasicDBObject`

这是最简单的。 创建`BasicDBObject`的实例，填充数据并调用`collection.insert()`方法。

```java
BasicDBObject document = new BasicDBObject();
document.put("name", "lokesh");
document.put("website", "howtodoinjava.com");

BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("addressLine1", "Sweet Home");
documentDetail.put("addressLine2", "Karol Bagh");
documentDetail.put("addressLine3", "New Delhi, India");

document.put("address", documentDetail);

collection.insert(document);

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98fe"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

```

## 2）使用`DBObjectBuilder`在集合中插入文档

与上面的示例非常相似，仅使用`DBObjectBuilder`来构建`DBObject`。

```java
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
		.add("name", "lokesh")
		.add("website", "howtodoinjava.com");

BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("addressLine1", "Some address")
.add("addressLine2", "Karol Bagh")
.add("addressLine3", "New Delhi, India");

documentBuilder.add("address", documentBuilderDetail.get());

collection.insert(documentBuilder.get());

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98ff"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

```

## 3）使用`java.util.HashMap`构建`BasicDBObject`并插入到集合中

在这里，您首先将数据放入哈希图中，然后使用该哈希图构建`BasicDBObject`。

```java
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("name", "lokesh");
documentMap.put("website", "howtodoinjava.com");

Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("addressLine1", "Some address");
documentMapDetail.put("addressLine2", "Karol Bagh");
documentMapDetail.put("addressLine3", "New Delhi, India");

documentMap.put("address", documentMapDetail);

collection.insert(new BasicDBObject(documentMap));

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98fg"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

```

## 4）解析 JSON 以构建`DBObject`并插入到集合中

```java
String json = "{ 'name' : 'lokesh' , " +
				"'website' : 'howtodoinjava.com' , " +
				"'address' : { 'addressLine1' : 'Some address' , " +
							  "'addressLine2' : 'Karol Bagh' , " +
							  "'addressLine3' : 'New Delhi, India'}" +
							"}";

DBObject dbObject = (DBObject)JSON.parse(json);

collection.insert(dbObject);

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98fg"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

```

## 完整的示例和源代码

以上所有示例的完整工作代码如下：

```java
package examples.mongodb.crud;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;

public class MongoDBInsertDataExample 
{
	public static void main(String[] args) throws UnknownHostException 
	{
		MongoClient mongo = new MongoClient("localhost", 27017);
		DB db = mongo.getDB("howtodoinjava");
		DBCollection collection = db.getCollection("users");

		///Delete All documents before running example again
		WriteResult result = collection.remove(new BasicDBObject());
		System.out.println(result.toString());

		basicDBObject_Example(collection);

		basicDBObjectBuilder_Example(collection);

		hashMap_Example(collection);

		parseJSON_Example(collection);

		DBCursor cursor = collection.find();
		while(cursor.hasNext()) {
		    System.out.println(cursor.next());
		}
	}

	private static void basicDBObject_Example(DBCollection collection){
		BasicDBObject document = new BasicDBObject();
		document.put("name", "lokesh");
		document.put("website", "howtodoinjava.com");

		BasicDBObject documentDetail = new BasicDBObject();
		documentDetail.put("addressLine1", "Sweet Home");
		documentDetail.put("addressLine2", "Karol Bagh");
		documentDetail.put("addressLine3", "New Delhi, India");

		document.put("address", documentDetail);

		collection.insert(document);
	} 

	private static void basicDBObjectBuilder_Example(DBCollection collection){
		BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
				.add("name", "lokesh")
				.add("website", "howtodoinjava.com");

		BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
		.add("addressLine1", "Some address")
		.add("addressLine2", "Karol Bagh")
		.add("addressLine3", "New Delhi, India");

		documentBuilder.add("address", documentBuilderDetail.get());

		collection.insert(documentBuilder.get());
	}

	private static void hashMap_Example(DBCollection collection){
		Map<String, Object> documentMap = new HashMap<String, Object>();
		documentMap.put("name", "lokesh");
		documentMap.put("website", "howtodoinjava.com");

		Map<String, Object> documentMapDetail = new HashMap<String, Object>();
		documentMapDetail.put("addressLine1", "Some address");
		documentMapDetail.put("addressLine2", "Karol Bagh");
		documentMapDetail.put("addressLine3", "New Delhi, India");

		documentMap.put("address", documentMapDetail);

		collection.insert(new BasicDBObject(documentMap));
	}

	private static void parseJSON_Example(DBCollection collection){
		String json = "{ 'name' : 'lokesh' , " +
						"'website' : 'howtodoinjava.com' , " +
						"'address' : { 'addressLine1' : 'Some address' , " +
									  "'addressLine2' : 'Karol Bagh' , " +
									  "'addressLine3' : 'New Delhi, India'}" +
									"}";

		DBObject dbObject = (DBObject)JSON.parse(json);

		collection.insert(dbObject);
	}

}

Output:

{ "serverUsed" : "localhost/127.0.0.1:27017" , "connectionId" : 3 , "n" : 4 , "syncMillis" : 0 , "writtenTo" :  null  , "err" :  null  , "ok" : 1.0}
{ "_id" : { "$oid" : "538d5b3936417871aa391d20"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}
{ "_id" : { "$oid" : "538d5b3936417871aa391d21"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Some address" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}
{ "_id" : { "$oid" : "538d5b3936417871aa391d22"} , "address" : { "addressLine3" : "New Delhi, India" , "addressLine2" : "Karol Bagh" , "addressLine1" : "Some address"} , "website" : "howtodoinjava.com" , "name" : "lokesh"}
{ "_id" : { "$oid" : "538d5b3936417871aa391d23"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Some address" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

```

**祝您学习愉快！**