安装

Install MongoDB Community Edition on Ubuntu

启动

sudo systemctl start mongod
sudo systemctl status mongod

Docker

Dockerhub - mongo

docker pull mongo:7.0.0

docker run -d \
  --name mongodb \
  --restart unless-stopped \
  -v /data/mongodb:/data/db \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=mongoadmin \
  -e MONGO_INITDB_ROOT_PASSWORD=secret \
  mongo:7.0.0

配置 TLS

Configure mongod and mongos for TLS/SSL

docker run -d \
  --name mongodb \
  --restart unless-stopped \
  -v /data/mongodb:/data/db \
  -v /home/your_username/.ssl:/etc/ssl/mongodb \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=your_username \
  -e MONGO_INITDB_ROOT_PASSWORD=your_password \
  mongo:latest \
  mongod --tlsMode requireTLS \
  --tlsCAFile /etc/ssl/mongodb/ca.pem \
  --tlsCertificateKeyFile /etc/ssl/mongodb/mongodb.pem

或者通过配置文件 mongod.conf 设置

net:
   tls:
      mode: requireTLS
      certificateKeyFile: /etc/ssl/mongodb/mongodb.pem
      CAFile: /etc/ssl/mongodb/ca.pem

再启动 docker 镜像

docker run -d \
  --name mongodb \
  --restart unless-stopped \
  -v /data/mongodb:/data/db \
  -v $(pwd)/mongod.conf:/etc/mongod.conf \
  -v /home/your_username/.ssl:/etc/ssl/mongodb \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=your_username \
  -e MONGO_INITDB_ROOT_PASSWORD=your_password \
  mongo:latest \
  mongod --config /etc/mongod.conf

Shell

Install mongosh

# enter mongo shell
mongosh --host <host> --port <port> -u <user> -p <pass> # 5.X+

# show all databases
show dbs

# select database
use <db_name>

# show all collections
show collections

# find one
db.<collection_name>.findOne()
db.<collection_name>.findOne({name: "Tom"})

Python SDK

https://pymongo.readthedocs.io/en/stable/tutorial.html

Import

from pymongo import MongoClient

Initiation

client = MongoClient()
client = MongoClient('localhost', 27017)
# creat or access database
db = client.test_db
db = client['test_db']
# creat or access collection
coll = db.test_collection
coll = db['test_collection']

List

client.list_databases()
client.list_database_names()
db.list_collections()
db.list_collection_names()

Insert and Query

# insert
coll.insert_one({'test': 'hello world', 'test2': 123})
coll.insert_many([{'Index': 1, 'Content': 'a'}
    {'Index': 2, 'Content': 'b'}
    {'Index': 3, 'Content': 'c'}
])
# find one
coll.find_one({'Content': 'b'})
# find all
coll.find()
coll.find({'Content': 'b'})
# find by id
id = coll.insert_one({'test': 'hello world'}).inserted_id
coll.find_one({"_id": id})

Modify

# update with $set
coll.update_one(
    {'test': 'hello world'}, 
    {
        '$set':{
            'update1': 'u1'
            'update2': 'u2'
        }
    }
)
# replace
coll.replace_one(
    {'test': 'hello world'}, 
    {
        'test': 'goodbye world',
        'test2': '456'
    }
)

Information

# print all collections
db.collection_names(include_system_collections=False)
# counts
coll.count()

Export to pandas

df = pd.DataFrame(list(collection.find()))

Go SDK

Quick Start

Quick Reference

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found")
	}

	uri := os.Getenv("MONGODB_URI")
	if uri == "" {
		log.Fatal("You must set your 'MONGODB_URI' environment variable.")
	}
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	title := "Back to the Future"

	var result bson.M
	err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).Decode(&result)
	if err == mongo.ErrNoDocuments {
		fmt.Printf("No document was found with the title %s\n", title)
		return
	}
	if err != nil {
		panic(err)
	}

	jsonData, err := json.MarshalIndent(result, "", "    ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", jsonData)
}

BSON

MongoDB - Work with BSON

  • D: slice
  • M: map
  • A: array
  • E: element of D
filter := bson.D{{"quantity", bson.D{{"$gt", 100}}}}

Javascript SDK

mongoose - Getting Started

备份

# 备份
mongodump
# 或者
mongodump -h dbhost -d dbname -o dbdirectory

# 恢复
mongorestore -h <hostname><:port> -d dbname <path>