连接数据库
Mongo mongo = null;
try {
// 通过连接字符串得到一个数据库实例的连接
mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
// Todo Auto-generated catch block
e.printStackTrace();
} catch (MongoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
获得数据库对象
// 获得一个数据库对象
DB db = mongo.getDB("solrdata");
// 指定安全授权信息
db.authenticate("lisa", "lisa".toCharArray());
// 声明一个collection1对象
DBCollection coll = db.getCollection("collection1");
存文档
// 声明一个document文档对象,用于存储数据
BasicDBObject doc = new BasicDBObject();
doc.put("name","lisa");
doc.put("age",18);
// 调用collection1的insert方法,将数据保存到数据库
coll.insert(doc);
更新文档
// 定义一个查询对象,相当于SQL的set语句
DBObject query = new BasicDBObject();
query.put("name","lisa");
// 定义一个更新对象,相当于SQL的set语句
DBObject update = new BasicDBObject();
update.put("age",20);
// 将查询对象和更新对象作为参数传给update中来完成更新
DBObject updateSetValue = new BasicDBObject("$set", update);
事务控制
// 开始事务控制,保证使用同一个DB
db.requestStart();
// 结束事务控制
db.requestDone();
计算文档数量
DBCollection coll = db.getCollection("collection1");
System.out.println(coll.getCount());
删除collection1集合所有索引
DBCollection coll = db.getCollection("collection1");
coll.dropIndexes;
用游标获取collection1集合中的所有文档
DBCursor cursor = coll.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
存文件夹中多个文档
List<DBObject> documents = new ArrayList<DBObject>();
String filepath = "/Users/lisa/Downloads/math";
File file = new File(filepath);
String[] filelist = file.list();
// 因为还有一个.DS_Store隐藏文件
for (int i = 1; i < filelist.length; i++) {
String jsonpath = filepath + "/" + filelist[i];
String jsonString = readJson(jsonpath);
DBObject test = (DBObject) JSON.parse(jsonString);
documents.add(test);
}
coll.insert(documents);
BsonDocument 和 Document 是类
BsonDocument 更适用于底层(内部)的 API,并且对于值类型的划分更细更严格
Document 对值类型的划分更宽泛,更适合高阶的 API
DBObject 是接口,需要一个具体的类 BasicDBObject 去实现它
具体参考ZhangQiang的博客