Skip to content

MongoDB 数据库

官方文档地址:https://www.mongodb.com/docs/manual/reference/method/

客户端推荐

  • Navicat Premium
  • DbGate
  • 自带命令行客户端 mongo 命令
    bash
    mongo --host {host} -u {user} -p {password} --authenticationDatabase admin

python 库

https://www.mongodb.com/docs/drivers/python-drivers/

【同步】pymongo

python
from pymongo import MongoClient

# mongo 配置
MONGO = {
    'host': '127.0.0.1',
    'port': 27017,
    'username': 'root',
    'password': '123456',
    'authSource': 'admin',
}
client = MongoClient(**MONGO)

db = client['test']

【异步】motor

https://motor.readthedocs.io/en/stable/tutorial-asyncio.html

python
import motor.motor_asyncio
# MONGO 与 pymongo 中的一样
client = motor.motor_asyncio.AsyncIOMotorClient(**MONGO)
  • pymongo 与 motor 两者查询语法几乎一样
  • motor 需要使用 async/await 关键字

docker-compose 启动 mongodb

yaml
version: "3"

services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: 123456
    volumes:
      - /data/mongo/db:/data/db
    ports:
      - 27017:27017

备份恢复

  • 可查看这篇文章:mongo 数据同步
  • 文章记录了 mongodumpmongorestore 的使用示例