java MongoDB 增加数据的四种方式
By:Roy.LiuLast updated:2014-04-17
前面实现了java 连接 MongoDB 数据库实现简单的增删改查的例子。作为入门确实足够了,但事实上还有很多其他的方法来做这些操作,比如增加数据,至少就有四种方法:
1. 利用 BasicDBObject 增加文档
2. 利用 BasicDBObjectBuilder 增加文档
3. 利用Map(HashMap) 增加文档
4. 利用json 字符串方式增加文档
假设要增加的文档模型如下:
下面的java代码,详细介绍了如何利用这四种方式来增加数据:
测试,启动 mongod 进程,运行测试java 程序,插入数据。再启动mongo 进程,查看插入的数据如下:
1. 利用 BasicDBObject 增加文档
2. 利用 BasicDBObjectBuilder 增加文档
3. 利用Map(HashMap) 增加文档
4. 利用json 字符串方式增加文档
假设要增加的文档模型如下:
database" : "yihaomen", "table" : "hosting", "detail" : { records : 99, index : "aliyun", active : "true" } }
下面的java代码,详细介绍了如何利用这四种方式来增加数据:
package com.yihaomen.mongodb.insert; 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.DBObject; import com.mongodb.Mongo; import com.mongodb.util.JSON; public class App { public static void main(String[] args) throws UnknownHostException { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("yihaomen"); DBCollection collection = db.getCollection("myinsert"); //insertByBasicDBObject(collection); //insertByBasicDBObjectBuilder(collection); //insertByHashMap(collection); insertByJsonString(collection); } public static void insertByBasicDBObject(DBCollection collection){ BasicDBObject document = new BasicDBObject(); document.put("database", "yihaomen"); document.put("table", "hosting"); BasicDBObject documentDetail = new BasicDBObject(); documentDetail.put("records", 99); documentDetail.put("index", "aliyun"); documentDetail.put("active", "true"); document.put("detail", documentDetail); collection.insert(document); } public static void insertByBasicDBObjectBuilder(DBCollection collection){ BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start() .add("database", "yihaomen") .add("table", "hosting"); BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start() .add("records", 99) .add("index", "aliyun") .add("active", "true"); documentBuilder.add("detail", documentBuilderDetail.get()); collection.insert(documentBuilder.get()); } public static void insertByHashMap(DBCollection collection){ MapdocumentMap = new HashMap (); documentMap.put("database", "yihaomen"); documentMap.put("table", "hosting"); Map documentMapDetail = new HashMap (); documentMapDetail.put("records", 99); documentMapDetail.put("index", "aliyun"); documentMapDetail.put("active", "true"); documentMap.put("detail", documentMapDetail); collection.insert(new BasicDBObject(documentMap)); } public static void insertByJsonString(DBCollection collection){ String json = "{'database' : 'yihaomen','table' : 'hosting'," + "'detail' : {'records' : 99, 'index' : 'aliyun', 'active' : 'true'}}}"; DBObject dbObject = (DBObject)JSON.parse(json); collection.insert(dbObject); } }
测试,启动 mongod 进程,运行测试java 程序,插入数据。再启动mongo 进程,查看插入的数据如下:
From:一号门
Previous:在Windows 下安装配置 MongoDB
COMMENTS