1. [代码]方法1
BasicDBObject document = new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", "99");
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
2. [代码]方法2
01 BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
02 .add("database", "mkyongDB")
03 .add("table", "hosting");
04
05 BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
06 .add("records", "99")
07 .add("index", "vps_index1")
08 .add("active", "true");
09
10 documentBuilder.add("detail", documentBuilderDetail.get());
11
12 collection.insert(documentBuilder.get());
3. [代码]方法3(使用Map)
01 Map<String, Object> documentMap = new HashMap<String, Object>();
02 documentMap.put("database", "mkyongDB");
03 documentMap.put("table", "hosting");
04
05 Map<String, Object> documentMapDetail = new HashMap<String, Object>();
06 documentMapDetail.put("records", "99");
07 documentMapDetail.put("index", "vps_index1");
08 documentMapDetail.put("active", "true");
09
10 documentMap.put("detail", documentMapDetail);
11
12 collection.insert(new BasicDBObject(documentMap));
4. [代码]方法4(使用JSON)
1 String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
2 "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
3
4 DBObject dbObject = (DBObject)JSON.parse(json);
5
6 collection.insert(dbObject);
5. [代码]完整示例 InsertDocumentApp.java
001 package com.mkyong.core;
002
003 import java.net.UnknownHostException;
004 import java.util.HashMap;
005 import java.util.Map;
006 import com.mongodb.BasicDBObject;
007 import com.mongodb.BasicDBObjectBuilder;
008 import com.mongodb.DB;
009 import com.mongodb.DBCollection;
010 import com.mongodb.DBCursor;
011 import com.mongodb.DBObject;
012 import com.mongodb.Mongo;
013 import com.mongodb.MongoException;
014 import com.mongodb.util.JSON;
015
016 /**
017 * MongoDB : Insert a Document
018 *
019 */
020 public class InsertDocumentApp {
021 public static void main(String[] args) {
022
023 try {
024
025 Mongo mongo = new Mongo("localhost", 27017);
026 DB db = mongo.getDB("yourdb");
027
028 // get a single collection
029 DBCollection collection = db.getCollection("dummyColl");
030
031 // BasicDBObject example
032 System.out.println("BasicDBObject example...");
033 BasicDBObject document = new BasicDBObject();
034 document.put("database", "mkyongDB");
035 document.put("table", "hosting");
036
037 BasicDBObject documentDetail = new BasicDBObject();
038 documentDetail.put("records", "99");
039 documentDetail.put("index", "vps_index1");
040 documentDetail.put("active", "true");
041 document.put("detail", documentDetail);
042更多精彩教程请关注: