MongoDB(18)如何向MongoDB集合中插入文档?

7 阅读3分钟

向MongoDB集合中插入文档的操作是数据库操作中非常基础且常见的一步。下面我们将详细介绍如何在不同的编程环境(包括MongoDB Shell、Node.js、Python和Java)中向MongoDB集合中插入文档。

在MongoDB Shell中插入文档

1. 启动MongoDB Shell

首先,打开终端或命令提示符,启动MongoDB Shell:

mongo

2. 选择数据库

选择你要插入文档的数据库:

use myDatabase

3. 插入文档

使用 db.collection.insertOnedb.collection.insertMany 方法向集合中插入文档。

插入单个文档:

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

插入多个文档:

db.myCollection.insertMany([
    { name: "Bob", age: 25, city: "San Francisco" },
    { name: "Charlie", age: 35, city: "Chicago" }
])

4. 验证插入

使用 find 方法验证文档是否插入成功:

db.myCollection.find().pretty()

使用Node.js插入文档

1. 安装MongoDB Node.js驱动

在终端中运行以下命令来安装MongoDB的Node.js驱动:

npm install mongodb

2. 创建并运行Node.js脚本

创建一个新的Node.js脚本文件(如 insertDocument.js)并添加以下代码:

const { MongoClient } = require('mongodb');

async function main() {
    const uri = "mongodb://localhost:27017";
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        // 连接到MongoDB服务器
        await client.connect();
        console.log("Connected to MongoDB");

        // 选择数据库
        const db = client.db('myDatabase');

        // 选择集合
        const collection = db.collection('myCollection');

        // 插入单个文档
        const insertOneResult = await collection.insertOne({ name: "Alice", age: 30, city: "New York" });
        console.log('Insert One Result:', insertOneResult);

        // 插入多个文档
        const insertManyResult = await collection.insertMany([
            { name: "Bob", age: 25, city: "San Francisco" },
            { name: "Charlie", age: 35, city: "Chicago" }
        ]);
        console.log('Insert Many Result:', insertManyResult);

    } finally {
        // 关闭连接
        await client.close();
    }
}

main().catch(console.error);

运行这个脚本:

node insertDocument.js

使用Python插入文档

1. 安装PyMongo

在终端中运行以下命令来安装PyMongo:

pip install pymongo

2. 创建并运行Python脚本

创建一个新的Python脚本文件(如 insert_document.py)并添加以下代码:

from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://localhost:27017/')

    # 选择数据库
    db = client['myDatabase']

    # 选择集合
    collection = db['myCollection']

    # 插入单个文档
    insert_one_result = collection.insert_one({ 'name': 'Alice', 'age': 30, 'city': 'New York' })
    print('Insert One Result:', insert_one_result.inserted_id)

    # 插入多个文档
    insert_many_result = collection.insert_many([
        { 'name': 'Bob', 'age': 25, 'city': 'San Francisco' },
        { 'name': 'Charlie', 'age': 35, 'city': 'Chicago' }
    ])
    print('Insert Many Result IDs:', insert_many_result.inserted_ids)

    # 关闭连接
    client.close()

if __name__ == '__main__':
    main()

运行这个脚本:

python insert_document.py

使用Java插入文档

1. 添加MongoDB Java驱动依赖

如果你使用的是Maven项目,添加以下依赖到你的 pom.xml 文件中:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.4.0</version>
</dependency>

2. 创建Java类并添加代码

创建一个新的Java类文件(如 InsertDocument.java)并添加以下代码:

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;

public class InsertDocument {
    public static void main(String[] args) {
        // 连接到MongoDB服务器
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 选择数据库
        MongoDatabase database = mongoClient.getDatabase("myDatabase");

        // 选择集合
        MongoCollection<Document> collection = database.getCollection("myCollection");

        // 插入单个文档
        Document doc1 = new Document("name", "Alice")
                            .append("age", 30)
                            .append("city", "New York");
        collection.insertOne(doc1);
        System.out.println("Inserted document: " + doc1.toJson());

        // 插入多个文档
        Document doc2 = new Document("name", "Bob")
                            .append("age", 25)
                            .append("city", "San Francisco");
        Document doc3 = new Document("name", "Charlie")
                            .append("age", 35)
                            .append("city", "Chicago");
        collection.insertMany(Arrays.asList(doc2, doc3));
        System.out.println("Inserted documents: " + doc2.toJson() + ", " + doc3.toJson());

        // 关闭连接
        mongoClient.close();
    }
}

编译并运行这个Java类:

javac -cp .:path/to/mongodb-driver-sync-4.4.0.jar InsertDocument.java
java -cp .:path/to/mongodb-driver-sync-4.4.0.jar InsertDocument

总结

在MongoDB中插入文档的步骤如下:

  1. 启动MongoDB Shell:使用 mongo 命令启动MongoDB Shell。
  2. 选择数据库:使用 use myDatabase 命令选择数据库。
  3. 插入文档:使用 db.myCollection.insertOnedb.myCollection.insertMany 方法插入文档。
  4. 验证插入:使用 db.myCollection.find().pretty() 方法验证文档是否插入成功。

此外,还可以使用Node.js、Python和Java来编写脚本或程序来插入文档。以上步骤和代码示例可以帮助你在不同编程语言和操作系统上实现向MongoDB集合中插入文档。