Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Node.js MongoDB 插入


插入集合

要将记录(在 MongoDB 中称为文档)插入集合,我们使用 insertOne() 方法。

MongoDB 中的文档与 MySQL 中的记录相同

insertOne() 方法的第一个参数是一个对象,包含要插入的文档中每个字段的名称和值。

它还接收一个回调函数,您可以在其中处理任何错误或插入结果

示例

将文档插入“customers”集合

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = { name: "Company Inc", address: "Highway 37" };
  dbo.collection("customers").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("插入了 1 个文档");
    db.close();
  });
});
运行示例 »

将上面的代码保存在名为“demo_mongodb_insert.js”的文件中,然后运行该文件

运行“demo_mongodb_insert.js”

C:\Users\您的用户名>node demo_mongodb_insert.js

将得到以下结果

插入了 1 个文档

注意: 如果您尝试将文档插入不存在的集合,MongoDB 将自动创建该集合。



插入多个文档

要在 MongoDB 中将多个文档插入集合,我们使用 insertMany() 方法。

insertMany() 方法的第一个参数是一个对象数组,包含要插入的数据。

它还接收一个回调函数,您可以在其中处理任何错误或插入结果

示例

将多个文档插入“customers”集合

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = [
    { name: 'John', address: 'Highway 71'},
    { name: 'Peter', address: 'Lowstreet 4'},
    { name: 'Amy', address: 'Apple st 652'},
    { name: 'Hannah', address: 'Mountain 21'},
    { name: 'Michael', address: 'Valley 345'},
    { name: 'Sandy', address: 'Ocean blvd 2'},
    { name: 'Betty', address: 'Green Grass 1'},
    { name: 'Richard', address: 'Sky st 331'},
    { name: 'Susan', address: 'One way 98'},
    { name: 'Vicky', address: 'Yellow Garden 2'},
    { name: 'Ben', address: 'Park Lane 38'},
    { name: 'William', address: 'Central st 954'},
    { name: 'Chuck', address: 'Main Road 989'},
    { name: 'Viola', address: 'Sideway 1633'}
  ];
  dbo.collection("customers").insertMany(myobj, function(err, res) {
    if (err) throw err;
    console.log("插入的文档数量:" + res.insertedCount);
    db.close();
  });
});
运行示例 »

将上面的代码保存在名为“demo_mongodb_insert_multiple.js”的文件中,然后运行该文件

运行“demo_mongodb_insert_multiple.js”

C:\Users\您的用户名>node demo_mongodb_insert_multiple.js

将得到以下结果

插入的文档数量:14

结果对象

执行 insertMany() 方法时,将返回一个结果对象。

结果对象包含有关插入如何影响数据库的信息。

上面示例中返回的对象如下所示

{
  result: { ok: 1, n: 14 },
  ops: [
    { name: 'John', address: 'Highway 71', _id: 58fdbf5c0ef8a50b4cdd9a84 },
    { name: 'Peter', address: 'Lowstreet 4', _id: 58fdbf5c0ef8a50b4cdd9a85 },
    { name: 'Amy', address: 'Apple st 652', _id: 58fdbf5c0ef8a50b4cdd9a86 },
    { name: 'Hannah', address: 'Mountain 21', _id: 58fdbf5c0ef8a50b4cdd9a87 },
    { name: 'Michael', address: 'Valley 345', _id: 58fdbf5c0ef8a50b4cdd9a88 },
    { name: 'Sandy', address: 'Ocean blvd 2', _id: 58fdbf5c0ef8a50b4cdd9a89 },
    { name: 'Betty', address: 'Green Grass 1', _id: 58fdbf5c0ef8a50b4cdd9a8a },
    { name: 'Richard', address: 'Sky st 331', _id: 58fdbf5c0ef8a50b4cdd9a8b },
    { name: 'Susan', address: 'One way 98', _id: 58fdbf5c0ef8a50b4cdd9a8c },
    { name: 'Vicky', address: 'Yellow Garden 2', _id: 58fdbf5c0ef8a50b4cdd9a8d },
    { name: 'Ben', address: 'Park Lane 38', _id: 58fdbf5c0ef8a50b4cdd9a8e },
    { name: 'William', address: 'Central st 954', _id: 58fdbf5c0ef8a50b4cdd9a8f },
    { name: 'Chuck', address: 'Main Road 989', _id: 58fdbf5c0ef8a50b4cdd9a90 },
    { name: 'Viola', address: 'Sideway 1633', _id: 58fdbf5c0ef8a50b4cdd9a91 } ],
  insertedCount: 14,
  insertedIds: [
    58fdbf5c0ef8a50b4cdd9a84,
    58fdbf5c0ef8a50b4cdd9a85,
    58fdbf5c0ef8a50b4cdd9a86,
    58fdbf5c0ef8a50b4cdd9a87,
    58fdbf5c0ef8a50b4cdd9a88,
    58fdbf5c0ef8a50b4cdd9a89,
    58fdbf5c0ef8a50b4cdd9a8a,
    58fdbf5c0ef8a50b4cdd9a8b,
    58fdbf5c0ef8a50b4cdd9a8c,
    58fdbf5c0ef8a50b4cdd9a8d,
    58fdbf5c0ef8a50b4cdd9a8e,
    58fdbf5c0ef8a50b4cdd9a8f
    58fdbf5c0ef8a50b4cdd9a90,
    58fdbf5c0ef8a50b4cdd9a91 ]
}

属性的值可以这样显示

示例

返回插入的文档数量

console.log(res.insertedCount)

将产生以下结果

14

_id 字段

如果您没有指定 _id 字段,那么 MongoDB 将为您添加一个,并为每个文档分配一个唯一的 ID。

在上面的示例中,没有指定 _id 字段,从结果对象中可以看出,MongoDB 为每个文档分配了一个唯一的 _id。

如果您确实指定了 _id 字段,则该值必须在每个文档中都是唯一的

示例

在“products”表中插入三条记录,并指定 _id 字段

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = [
    { _id: 154, name: 'Chocolate Heaven'},
    { _id: 155, name: 'Tasty Lemon'},
    { _id: 156, name: 'Vanilla Dream'}
  ];
  dbo.collection("products").insertMany(myobj, function(err, res) {
    if (err) throw err;
    console.log(res);
    db.close();
  });
});
运行示例 »

将上面的代码保存在名为“demo_mongodb_insert_id.js”的文件中,然后运行该文件

运行“demo_mongodb_insert_id.js”

C:\Users\您的用户名>node demo_mongodb_insert_id.js

将得到以下结果

{
  result: { ok: 1, n: 3 },
  ops: [
    { _id: 154, name: 'Chocolate Heaven },
    { _id: 155, name: 'Tasty Lemon },
    { _id: 156, name: 'Vanilla Dream } ],
  insertedCount: 3,
  insertedIds: [
    154,
    155,
    156 ]
}

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.