MongoDB插入文档

要在 MongoDB 中插入文档,可以使用 db.collection.insertOne() 方法或 db.collection.insertMany() 方法,如下所示:

db.mycollection.insertOne({ name: "John Doe", age: 30 })
db.mycollection.insertMany([
  { name: "Jane Smith", age: 25 },
  { name: "Bob Johnson", age: 40 }
])

db.collection.insertOne()是MongoDB Node.js驱动程序提供的一个方法,用于向指定集合中插入一条文档。该方法的语法如下:

db.collection.insertOne(document, options)

其中,document是要插入的文档对象,options是一个可选的配置对象,用于指定插入的选项。options可以包含以下选项:

  • w:指定写入的安全性等级,取值为 0、1、或 "majority"。
  • j:指定写入是否需要持久化到磁盘。
  • serializeFunctions:指定是否将函数序列化后再插入数据库中。
  • forceServerObjectId:指定是否强制使用MongoDB服务器生成的ObjectId。
  • bypassDocumentValidation:指定是否绕过文档验证器,直接插入文档。

db.collection.insertOne()方法返回一个Promise对象,当插入操作完成后,Promise对象会被解决,并返回一个包含插入结果的对象。如果插入操作失败,Promise对象将被拒绝,并返回一个包含错误信息的对象。

下面是一个示例,演示如何使用db.collection.insertOne()方法向MongoDB数据库中插入一条文档:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/myproject';

MongoClient.connect(url, function(err, client) {
  console.log('Connected successfully to server');

  const db = client.db('myproject');
  const collection = db.collection('documents');

  const document = { a: 1, b: 2, c: 3 };

  collection.insertOne(document, function(err, result) {
    console.log('Inserted a document into the documents collection');
    console.log(result);
    client.close();
  });
});

https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/#db.collection.insertOne 官方文档