最近一直在做数据接入相关的工作,刚好用到了MongoDb,下面就简单介绍下MongoDB连接及查询语法。
MongoDB
MongoDB 是一个高性能,开源,无模式的文档型数据库,开发语言是C++。它在许多场景下可用于替代传统的关系型数据库或键/值存储方式。MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库中功能最丰富、最像关系数据库的。
基本概念
在MongoDB中基本的概念是数据库、集合、文档,如下表所示。
Java Demo
mvn 依赖
<!--mongoDb driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.0</version>
</dependency>
jdbc连接 Demo
public class MongoDBDemo{
private MongoClient client;
private MongodbConnection connection;
private String uriFormat = "mongodb://%s:%s@%s/%s";
private void initClient() {
if (CollectionUtils.isEmpty(connection.getAddress())) {
return;
}
try {
String seedStr = connection.getAddress().stream().collect(Collectors.joining(","));
String uriStr = String.format(uriFormat, connection.getUsername(), connection.getPassword(), seedStr,
connection.getDatabase());
if (StringUtil.isNotEmpty(connection.getReplSetName())) {
uriStr = uriStr + "?replicaSet=" + connection.getReplSetName();
} // end if
// 另一种通过URI初始化
// mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
MongoClientURI connectionUri = new MongoClientURI(uriStr);
this.client = new MongoClient(connectionUri);
} catch (Exception e) {
log.error("mongodb connection fail,throws exception", e);
throw new BizRuntimeException(ErrorCode.getError(SqlExecuteError.MONGODB_CONNECTION_TIMEOUT));
} // end try-carch
}
}
MongoDB 查询语法
查询语法详细参考 官网。
常用查询语法Java Demo
1 获取Table
/***
* 获取collection = table
*
* @param tableName
* @return
*/
public MongoCollection<Document> getTable(String tableName) {
MongoDatabase db = client.getDatabase(connection.getDatabase());
return db.getCollection(tableName);
}
2 First Doc
一般用于预览MongoDB某个DB中的Doc信息。
/***
* 获取集合的第一个文档
*
* @param tableName
* @return
*/
public Document getFirstDoc(String tableName) throws Exception {
MongoDatabase db = client.getDatabase(connection.getDatabase());
MongoCollection<Document> table = db.getCollection(tableName);
MongoCursor<Document> iter = table.find().iterator();
Document document = null;
while (iter.hasNext()) {
document = iter.next();
document.remove(CommonConstants.MONGODB_ID);
break;
} // end while
return document;
}