该文章使用的Mongodb的版本为3.0.0
建立连接:
MongoClient client = new MongoClient(new ServerAddress(ip, port));
获取数据库:
MongoDatabase db=client.getDatabase(“数据库名称”);
根据数据库获取所有集合名:
MongoIterable<String> listCollectionNames = db.listCollectionNames();
MongoCursor<String> colIt = listCollectionNames.iterator();
while (colIt.hasNext()) {
colIt.next();//取出每一个集合名
}
集合操作:
获取集合
MongoCollection<Document> collection = db.getCollection(colName);
collection.count() //统计集合中的记录数
collection.count(new Document("字段名", 字段值)); //统计包含指定字段值的记录数
增加集合
db.createCollection("集合名");
删除集合
collection.drop();
数据操作:
删除
DeleteResult deleteMany = collection.deleteMany(new Document("字段名", 字段值)); //删除多条记录
deleteMany.getDeletedCount(); //统计删除的记录数
增加
Document document = new Document();
document.put(key, value);
collection.insertOne(document); //插入一条记录
collection.insertMany(List<Document>); //插入多条
更新
Document queryDoc = new Document("字段名", 值);
Document updateDoc = new Document("$set", new Document("字段名", 新的值));
UpdateResult updateMany=collection.updateMany(queryDoc, updateDoc); //更新数据</span>
updateMany.getModifiedCount(); //统计更新的记录数
查找
MongoCursor<Document> resIter = collection.find(new Document(QueryOperators.OR, List<Document>)).iterator(); //or条件查询
Document doc = collection.find(new Document("_id", new ObjectId(Id))).first(); //根据id查询
模糊查询
String[] attrNames = { "字段名" };// 需要模糊查询的参数
List<Document> cdtList = new ArrayList<Document>();
String condition="要查询的值";
condition = condition == null ? "" : condition.toUpperCase(); // 转换成大写
String regex = "^.*" + condition+ ".*$"; // 全部匹配
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // 使用模糊查询
for (int index = 0; null != attrNames && index < attrNames.length; index++) {
cdtList.add(new Document(attrNames[index], pattern)); // 拼装条件
}
Document queryDoc = new Document(); // 查询条件,put(key,value)
MongoCursor<Document> resIter = mgcl.find(Filters.and(new Document(QueryOperators.OR, cdtList), queryDoc)).iterator();
分页:
Document document = new Document();// 设置分页的条件
document.put("字段名", 值);
MongoCursor<Document> cursor =collection.find(document).skip(pageIndex * 每页记录数).limit(每页记录数).iterator(); // 设置分页参数
建立索引:
collection.createIndex(new Document("字段名", 1)); // 建立索引
MongoCursor<String> iterator = collection.distinct("字段名", String.class).iterator(); // 使用mongo去重