1.docker安装mongodb
1.1docker-compose容器编排
1.2mongodb的设置
mongodb很特殊的一点就是必须要进行权限设置,下面是登录的mongodb后,选择admin并进行权限认证,然后通过use可以创建出一个新的库lkp,然后可以通过db.createUser创建对应可以操作该库的用户和权限,对应的可以参考文档:https://cloud.tencent.com/developer/article/1506715
use admin
db.auth("admin","123456")
use lkp
db.createUser({ user: "root", pwd: "root", roles: [{ role: "dbAdmin", db: "lkp" },{ role: "readWrite", db: "lkp" }] })
2.python(FastApi)接入mongodb
2.1pymongo
pymongo是python用来操作mongodb的库,使用起来也非常简单。 首先需要下载该库,使用命令
pip install pymongo
之后便是在代码中引入了
from pymongo import MongoClient
DB_CLIENT = MongoClient('mongodb://admin:123456@10.219.36.167:27017')
DB = DB_CLIENT['admin']
2.2crud操作
首先顶一个数据模型,方便下面的操作
from pydantic import BaseModel
from typing import List
class Weather(BaseModel):
today: str
des: str
temperature: str
details: List[str]
day: str
update_time: int
下面就是对应的crud操作
from pymongo import MongoClient
from typing import List
def save(weather: Weather):
inserted_obj = DB.weather.insert_one(weather.dict())
return str(inserted_obj.inserted_id)
def batch_save(weather_list: List[Weather]):
data_list = []
for weather in weather_list:
data_list.append(weather.dict())
inserted_id_obj_list = DB.weather.insert_many(data_list)
inserted_id_list = []
for inserted_id_obj in inserted_id_obj_list:
inserted_id_list.append(inserted_id_obj.inserted_id)
return inserted_id_list
def get(query: dict):
result = []
date_cursor = DB.weather.find(query)
for x in date_cursor:
result.append(x)
return result
def delete(query: dict):
DB.weather.delete_many(query)
def update(weather: Weather):
query = {"day": weather.day}
values = {"$set": weather.dict()}
DB.weather.update_many(query, values)
3.java(spring)接入mongodb
3.1依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
3.2配置
spring:
data:
mongodb:
uri: mongodb://root:root@${myurl.mongodb}/lkp
3.3使用
@Autowired
private MongoTemplate mongoTemplate;
|