原文: https://howtodoinjava.com/mongodb/java-mongodb-insert-documents-in-collection-examples/

MongoDB 学习系列中,我们已经介绍了 MongoDB 基础知识在 Windows 中安装 MongoDB如何从集合中查询/选择文档 Examples”)。 在本教程中,我列出了 4 种可用于在 MongoDB 中向集合中插入或添加文档的方法。

  1. List of examples in this tutorial
  2. 1) Insert BasicDBObject in collection
  3. 2) Use DBObjectBuilder to insert document in collection
  4. 3) Use java.util.HashMap to build BasicDBObject and insert into collection
  5. 4) Parse JSON to build DBObject and insert into collection

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

  1. {
  2. "name":"lokesh",
  3. "website":"howtodoinjava.com",
  4. "address":{
  5. "addressLine1":"Some address",
  6. "addressLine2":"Karol Bagh",
  7. "addressLine3":"New Delhi, India"
  8. }
  9. }

1)在集合中插入BasicDBObject

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

  1. BasicDBObject document = new BasicDBObject();
  2. document.put("name", "lokesh");
  3. document.put("website", "howtodoinjava.com");
  4. BasicDBObject documentDetail = new BasicDBObject();
  5. documentDetail.put("addressLine1", "Sweet Home");
  6. documentDetail.put("addressLine2", "Karol Bagh");
  7. documentDetail.put("addressLine3", "New Delhi, India");
  8. document.put("address", documentDetail);
  9. collection.insert(document);
  10. Output:
  11. { "_id" : { "$oid" : "538d56a3364192189d4f98fe"} , "name" : "lokesh" , "website" : "howtodoinjava.com" ,
  12. "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

2)使用DBObjectBuilder在集合中插入文档

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

  1. BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
  2. .add("name", "lokesh")
  3. .add("website", "howtodoinjava.com");
  4. BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
  5. .add("addressLine1", "Some address")
  6. .add("addressLine2", "Karol Bagh")
  7. .add("addressLine3", "New Delhi, India");
  8. documentBuilder.add("address", documentBuilderDetail.get());
  9. collection.insert(documentBuilder.get());
  10. Output:
  11. { "_id" : { "$oid" : "538d56a3364192189d4f98ff"} , "name" : "lokesh" , "website" : "howtodoinjava.com" ,
  12. "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

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

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

  1. Map<String, Object> documentMap = new HashMap<String, Object>();
  2. documentMap.put("name", "lokesh");
  3. documentMap.put("website", "howtodoinjava.com");
  4. Map<String, Object> documentMapDetail = new HashMap<String, Object>();
  5. documentMapDetail.put("addressLine1", "Some address");
  6. documentMapDetail.put("addressLine2", "Karol Bagh");
  7. documentMapDetail.put("addressLine3", "New Delhi, India");
  8. documentMap.put("address", documentMapDetail);
  9. collection.insert(new BasicDBObject(documentMap));
  10. Output:
  11. { "_id" : { "$oid" : "538d56a3364192189d4f98fg"} , "name" : "lokesh" , "website" : "howtodoinjava.com" ,
  12. "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

4)解析 JSON 以构建DBObject并插入到集合中

  1. String json = "{ 'name' : 'lokesh' , " +
  2. "'website' : 'howtodoinjava.com' , " +
  3. "'address' : { 'addressLine1' : 'Some address' , " +
  4. "'addressLine2' : 'Karol Bagh' , " +
  5. "'addressLine3' : 'New Delhi, India'}" +
  6. "}";
  7. DBObject dbObject = (DBObject)JSON.parse(json);
  8. collection.insert(dbObject);
  9. Output:
  10. { "_id" : { "$oid" : "538d56a3364192189d4f98fg"} , "name" : "lokesh" , "website" : "howtodoinjava.com" ,
  11. "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

完整的示例和源代码

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

  1. package examples.mongodb.crud;
  2. import java.net.UnknownHostException;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import com.mongodb.BasicDBObject;
  6. import com.mongodb.BasicDBObjectBuilder;
  7. import com.mongodb.DB;
  8. import com.mongodb.DBCollection;
  9. import com.mongodb.DBCursor;
  10. import com.mongodb.DBObject;
  11. import com.mongodb.MongoClient;
  12. import com.mongodb.WriteResult;
  13. import com.mongodb.util.JSON;
  14. public class MongoDBInsertDataExample
  15. {
  16. public static void main(String[] args) throws UnknownHostException
  17. {
  18. MongoClient mongo = new MongoClient("localhost", 27017);
  19. DB db = mongo.getDB("howtodoinjava");
  20. DBCollection collection = db.getCollection("users");
  21. ///Delete All documents before running example again
  22. WriteResult result = collection.remove(new BasicDBObject());
  23. System.out.println(result.toString());
  24. basicDBObject_Example(collection);
  25. basicDBObjectBuilder_Example(collection);
  26. hashMap_Example(collection);
  27. parseJSON_Example(collection);
  28. DBCursor cursor = collection.find();
  29. while(cursor.hasNext()) {
  30. System.out.println(cursor.next());
  31. }
  32. }
  33. private static void basicDBObject_Example(DBCollection collection){
  34. BasicDBObject document = new BasicDBObject();
  35. document.put("name", "lokesh");
  36. document.put("website", "howtodoinjava.com");
  37. BasicDBObject documentDetail = new BasicDBObject();
  38. documentDetail.put("addressLine1", "Sweet Home");
  39. documentDetail.put("addressLine2", "Karol Bagh");
  40. documentDetail.put("addressLine3", "New Delhi, India");
  41. document.put("address", documentDetail);
  42. collection.insert(document);
  43. }
  44. private static void basicDBObjectBuilder_Example(DBCollection collection){
  45. BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
  46. .add("name", "lokesh")
  47. .add("website", "howtodoinjava.com");
  48. BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
  49. .add("addressLine1", "Some address")
  50. .add("addressLine2", "Karol Bagh")
  51. .add("addressLine3", "New Delhi, India");
  52. documentBuilder.add("address", documentBuilderDetail.get());
  53. collection.insert(documentBuilder.get());
  54. }
  55. private static void hashMap_Example(DBCollection collection){
  56. Map<String, Object> documentMap = new HashMap<String, Object>();
  57. documentMap.put("name", "lokesh");
  58. documentMap.put("website", "howtodoinjava.com");
  59. Map<String, Object> documentMapDetail = new HashMap<String, Object>();
  60. documentMapDetail.put("addressLine1", "Some address");
  61. documentMapDetail.put("addressLine2", "Karol Bagh");
  62. documentMapDetail.put("addressLine3", "New Delhi, India");
  63. documentMap.put("address", documentMapDetail);
  64. collection.insert(new BasicDBObject(documentMap));
  65. }
  66. private static void parseJSON_Example(DBCollection collection){
  67. String json = "{ 'name' : 'lokesh' , " +
  68. "'website' : 'howtodoinjava.com' , " +
  69. "'address' : { 'addressLine1' : 'Some address' , " +
  70. "'addressLine2' : 'Karol Bagh' , " +
  71. "'addressLine3' : 'New Delhi, India'}" +
  72. "}";
  73. DBObject dbObject = (DBObject)JSON.parse(json);
  74. collection.insert(dbObject);
  75. }
  76. }
  77. Output:
  78. { "serverUsed" : "localhost/127.0.0.1:27017" , "connectionId" : 3 , "n" : 4 , "syncMillis" : 0 , "writtenTo" : null , "err" : null , "ok" : 1.0}
  79. { "_id" : { "$oid" : "538d5b3936417871aa391d20"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}
  80. { "_id" : { "$oid" : "538d5b3936417871aa391d21"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Some address" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}
  81. { "_id" : { "$oid" : "538d5b3936417871aa391d22"} , "address" : { "addressLine3" : "New Delhi, India" , "addressLine2" : "Karol Bagh" , "addressLine1" : "Some address"} , "website" : "howtodoinjava.com" , "name" : "lokesh"}
  82. { "_id" : { "$oid" : "538d5b3936417871aa391d23"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Some address" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

祝您学习愉快!