mongodb 安装和使用

30 阅读1分钟

介绍

mongodb是一个文档型的NoSql数据库。

mongodb是2009年首次发布,开发的初衷是为了解决关系数据库在大数据处理下的局限性,也是现在最受欢迎的Nosql数据库之一。

文档(Document)MongoDB 最核心的数据结构,就是一个 JSON 对象。

集合(Collection)类似表,但没有固定 schema。

安装 mongodb 和 mongodb-shell

官方地址:www.mongodb.com/try/downloa…

www.mongodb.com/try/downloa…

下载完解压,这边使用的是ubuntu22.04.4

执行命令:

tar -zxvf mongodb-linux-x86_64-ubuntu2204-8.2.2.tgz 
tar -zxvf mongosh-2.5.10-linux-x64.tgz 
mv mongodb-linux-x86_64-ubuntu2204-8.2.2 mongodb 
//添加 mongodb.conf文件 创建data文件夹 
net: 
    bindIp: 0.0.0.0 
    port: 27017 
storage: 
    dbPath: /opt/mongodb/data/db 
systemLog: 
    destination: file 
    path: /opt/mongodb/data/logs/mongod.log 
    logAppend: true 
-------------------------- 
//添加path 配置 
vim /etc/profile 
//添加 mongosh地址 
export MONGOSH_HOME="/opt/mongosh" 
------------- 
source /etc/profile 
//启动mongodb 
./bin/mongd -f mongodb.conf & 
//进入数据库 
mongosh

项目使用

1.先导入包


<dependency> 
    <groupId>org.mongodb</groupId> 
    <artifactId>mongodb-driver-sync</artifactId> 
    <version>${mongodb.version}</version> 
</dependency> 
<dependency> 
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-core</artifactId> 
    <version>${mongodb.version}</version>
</dependency> 
<dependency> 
    <groupId>org.mongodb</groupId> 
    <artifactId>bson</artifactId>
    <version>${mongodb.version}</version> 
</dependency>

2.创建连接

CodecRegistry registry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())); 
MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(new ConnectionString(uri)).codecRegistry(registry).build(); 
MongoClient client = MongoClients.create(settings);

3.使用

3.1修改
Bson bson = Filters.eq("id", id); Document doc = client.toDocument(object); 
UpdateOptions options = new UpdateOptions().upsert(true);
//如果没有查找到直接添加 
client.getDatabase(database).getCollection(tableName).updateOne(bson, doc, options);
3.2查询
//查询单个 
Document document = client.getDatabase(database).getCollection(tableName).find(Filters.eq("id", id)).first(); 
//查询列表 
List<Document> list = client.getDatabase(database).getCollection(tableName).find().skip((page - 1) * size).limit(size).into(new ArrayList<>()); 
//查询数量 
long count = client.getDatabase(database).getCollection(tableName).countDocuments()
3.3删除
//删除一个
long result = client.getDatabase(database).getCollection(tableName).deleteOne(Filters.eq("id", id)).getDeletedCount(); 
//删除多个 
long result = client.getDatabase(database).getCollection(tableName).deleteMany(Filters.in("id", ids)).getDeletedCount();