MongoDB collection.insertOne()
方法使用指南
collection.insertOne()
是 MongoDB 提供的一种用于向指定集合中插入单个文档的方法。它允许用户将一组键值对作为新记录保存到数据库中,适用于多种编程语言及其对应的 MongoDB 驱动程序。
方法定义
在 MongoDB 中,insertOne()
方法的主要作用是向某个特定的集合(Collection)中插入一条新的文档(Document)。这条文档通常以 JSON 或 BSON 格式表示,包含一系列字段和对应的数据值。
参数描述
该方法接受两个参数:
- document: 要插入的目标文档对象,形式为键值对结构。
- options (可选): 可配置选项,例如绕过文档验证 (
bypassDocumentValidation
) 等高级设置。
返回的结果是一个包含 _id
字段的对象,表明所插入文档的身份标识符。
示例代码展示
下面是一些不同环境下调用 insertOne()
的实例演示:
Python 版本
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]
new_user = {
"name": "Alice", "age": 25}
result = collection.insert_one(new_user)
print(f"Inserted user with ID: {
result.inserted_id}")
JavaScript/Node.js 版本
const {
MongoClient } = require('mongodb');
async function run() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('sample_database');
const users = database.collection('users');