使用Python插入嵌套MongoDB文档

2023-04-15 00:00:00 文档 插入 嵌套

插入嵌套MongoDB文档需要使用MongoDB的语法和Python的代码,下面是详细的步骤和代码演示:

步骤1:导入pymongo模块并连接MongoDB数据库

import pymongo

client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['testdb']

步骤2:定义一个嵌套的MongoDB文档(字典类型)

document = {
    "name": "Alice",
    "age": 25,
    "address": {
        "street": "123 Main Street",
        "city": "New York",
        "state": "NY",
        "zip": "12345"
    },
    "interests": ["coding", "reading", "traveling"],
    "website": {
        "url": "https://pidancode.com",
        "name": "皮蛋编程"
    }
}

步骤3:插入嵌套的MongoDB文档到指定集合中

collection = db['users']
collection.insert_one(document)

完整代码演示:

import pymongo

client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['testdb']

# 定义嵌套文档
document = {
    "name": "Alice",
    "age": 25,
    "address": {
        "street": "123 Main Street",
        "city": "New York",
        "state": "NY",
        "zip": "12345"
    },
    "interests": ["coding", "reading", "traveling"],
    "website": {
        "url": "https://pidancode.com",
        "name": "皮蛋编程"
    }
}

# 插入文档
collection = db['users']
collection.insert_one(document)

相关文章