Karp 的技术博客

MongoDB 中,你可以使用 insertOneinsertMany 方法向集合中插入文档。以下是插入文档的基本步骤:

比如插入单个文档:
使用 insertOne 方法可以向集合中插入单个文档。

// 导入 MongoDB 驱动
const MongoClient = require('mongodb').MongoClient;

// 定义数据库连接字符串和数据库名称
const url = 'mongodb://localhost:27017';
const dbName = 'your_database';

// 创建 MongoClient 实例
const client = new MongoClient(url, { useNewUrlParser: true });

// 连接到 MongoDB 服务器
client.connect(function(err) {
  if (err) throw err;

  // 选择要插入文档的集合
  const db = client.db(dbName);
  const collection = db.collection('your_collection');

  // 插入单个文档
  collection.insertOne({
    key1: 'value1',
    key2: 'value2',
    // 其他字段...
  }, function(err, result) {
    if (err) throw err;
    console.log('插入的文档数量:', result.insertedCount);

    // 关闭数据库连接
    client.close();
  });
});

mongodb

版权属于:karp
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
更新于: 2015年09月10日 04:15
10

目录

来自 《如何在 MongoDB 中插入文档?》