MongoDB基础使用

2023/11/12 Database 共 2447 字,约 7 分钟

MongoDB基础使用

安装

mac m1只支持4.4,否则cpu不兼容。

docker pull mongo:4.4

docker run -d \
  --name mongodb \
  -p 27017:27017 \
  -v ~/mongo_data:/data/db \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  mongo:4.4

密码就是password

数据库操作软件

mongodb compass, 是一款mac的免费软件。

brew install --cask mongodb-compass
open /Applications/MongoDB\ Compass.app

基本操作

collection就是对应了一个 table, 更新插入会自动创建不存在的collection。 database也是这样。

操作的返回结果和输入都是dict形式,每个record都有一个_id属性,它在table里唯一。

连接

import logging

from pymongo import MongoClient
import atexit

# MongoDB 连接 URI(替换为你的数据库用户名、密码)
uri = "mongodb://admin:password@localhost:27017/?authSource=admin"
client = None
try:
    client = MongoClient(uri)
    # 在程序退出时自动关闭 MongoDB 客户端
    atexit.register(client.close)
except Exception as ex:
    logging.error(ex)

def get_db_collection(table="stock"):
    if client is None:
        logging.error("MongoDB client is None")
        return None
    # 选择数据库
    db = client["trading"]  # 替换为你的数据库名称
    collection = db[table]  # 替换为你的集合名称
    return collection

  
  
  
  

使用

    collection = get_db_collection()

    # 插入多个文档
    documents = [
        {"name": "Alice", "age": 25, "city": "Los Angeles"},
        {"name": "Bob", "age": 28, "city": "Chicago"}
    ]
    collection.insert_many(documents)
    for doc in collection.find():
        print(doc)
    # 查询特定文档
    query = {"name": "John"}
    result = collection.find_one(query)
    print(result)

    # query = {"name": "John"}
    # collection.delete_one(query)
    # query = {"city": "San Francisco"}
    query = {}
    collection.delete_many(query)


查找

db.collection.find(query, projection)
  • query:用于查找文档的查询条件。默认为 {},即匹配所有文档。
  • projection(可选):指定返回结果中包含或排除的字段。
查找单个文档,并只返回指定字段:
db.myCollection.findOne(
    { name: "Alice" },
    { name: 1, age: 1, _id: 0 } 
);
1就是存在,0就是不存在

query的高级用法

1、使用比较操作符

MongoDB 支持多种比较操作符,如 $gt、$lt、$gte、$lte、$eq、$ne 等。

查找年龄大于 25 的文档:

db.myCollection.find({ age: { $gt: 25 } });

判断要存在某个字段 可以$exists: True

2、使用逻辑操作符

MongoDB 支持多种逻辑操作符,如 $and、$or、$not、$nor 等。

查找年龄大于 25 且城市为 “New York” 的文档:

db.myCollection.find({
    $and: [
        { age: { $gt: 25 } },
        { city: "New York" }
    ]
});

find返回的是个cursor, 可以直接遍历

    for doc in collection.find():
        print(doc)

插入

db.myCollection.insertOne({
    name: "Alice",
    age: 25,
    city: "New York"
});

db.myCollection.insertMany([
    { name: "Bob", age: 30, city: "Los Angeles" },
    { name: "Charlie", age: 35, city: "Chicago" }
]);


save() 方法在插入文档时表现得类似于 insertOne()。

如果文档包含 _id 字段且已存在,则该文档会被更新;如果文档不包含 _id 字段或 _id 不存在,则会插入一个新文档。

db.myCollection.save({
    _id: ObjectId("60c72b2f9b1d8b5a5f8e2b2d"),
    name: "David",
    age: 40,
    city: "San Francisco"
});

删除

db.myCollection.deleteOne({ name: "Alice" });

db.myCollection.deleteMany({ status: "inactive" });

更新

db.myCollection.updateOne(
    { name: "Alice" },                // 过滤条件
    { $set: { age: 26 } },            // 更新操作
    { upsert: false }                 // 可选参数
);

db.myCollection.updateMany(
    { age: { $lt: 30 } },             // 过滤条件
    { $set: { status: "active" } },   // 更新操作
    { upsert: false }                  // 可选参数
);


Search

    Table of Contents