使用Java操作MongoDB - Insert

Insert
Can use the below 4 methods to implement:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Mongo mg = new Mongo("localhost", 27017);
// get db
db = mg.getDB("CRUD");
// get collection
dc = db.getCollection("test");

//1st save
BasicDBObject doc = new BasicDBObject();
doc.put("name", "add");
doc.put("method", "save");
dc.save(doc);

//2nd insert (using BasicDBObject)
BasicDBObject document = new BasicDBObject();
document.put("database", "mongo");
document.put("table", "testing");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", "99");
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
dc.insert(document);

//3rd insert (using BasicDBObjectBuilder)
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add("database", "mkyongDB")
.add("table", "hosting");
dc.insert(documentBuilder.get());

//3rd insert (using Map)
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("name", "insert");
documentMap.put("method", "map");
dc.insert(new BasicDBObject(documentMap));

//4th insert (using JSON --> simplest way)
String json = "{name : 'insert', recommend : true, method : 'JSON'}";
DBObject dbObject = (DBObject) JSON.parse(json);
dc.insert(dbObject);

Insert Multiple Documents
For multiple data, we can implement this with previous 4th method:

1
2
3
4
5
6
7
8
String[] myList = {"{number : 1, name: 'hulu1', tags: ['test', 'develop'], comments: [{user: 'hu', like: 0}, {user: 'lu', like: 1}]}"};	
InsertMultipleDocuments(myList);

public static void InsertMultipleDocuments(String[] array) {
for (String json : array) {
DBObject dbObject = (DBObject) JSON.parse(json);
dc.insert(dbObject);
}

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!