- 节点和 MongoDB 教程
- 节点和 MongoDB - 主页
- 节点和 MongoDB - 概述
- Node 和 MongoDB - 环境设置
- 节点和 MongoDB 示例
- Node 和 MongoDB - 连接数据库
- Node 和 MongoDB - 显示数据库
- Node 和 MongoDB - 删除数据库
- Node & MongoDB - 创建集合
- Node 和 MongoDB - 删除集合
- Node & MongoDB - 显示集合
- Node 和 MongoDB - 插入文档
- Node & MongoDB - 选择文档
- Node 和 MongoDB - 更新文档
- Node & MongoDB - 删除文档
- Node 和 MongoDB - 嵌入式文档
- Node & MongoDB - 限制记录
- Node 和 MongoDB - 记录排序
- 节点和 MongoDB 有用资源
- Node 和 MongoDB - 快速指南
- Node 和 MongoDB - 有用的资源
- Node 和 MongoDB - 讨论
Node 和 MongoDB - 插入文档
要在数据库集合中插入文档,可以使用collection.insertOne()或 collection.insertMany()方法插入一个或多个文档。
database.collection("sampleCollection").insertOne(firstDocument, function(error, res) {
if (error) throw error;
console.log("1 document inserted");
});
database.collection("sampleCollection").insertMany(documents, function(error, res) {
if (error) throw error;
console.log("Documents inserted: " + res.insertedCount);
});
例子
尝试以下示例在 mongodb 集合中插入文档 -
将以下示例复制并粘贴为 mongodb_example.js -
const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://localhost:27017/";
const firstDocument = {
First_Name : 'Mahesh',
Last_Name : 'Parashar',
Date_Of_Birth: '1990-08-21',
e_mail: 'mahesh_parashar.123@gmail.com',
phone: '9034343345'
};
const documents = [{
First_Name : 'Radhika',
Last_Name : 'Sharma',
Date_Of_Birth: '1995-09-26',
e_mail: 'radhika_sharma.123@gmail.com',
phone: '9000012345'
},
{
First_Name : 'Rachel',
Last_Name : 'Christopher',
Date_Of_Birth: '1990-02-16',
e_mail: 'rachel_christopher.123@gmail.com',
phone: '9000054321'
},
{
First_Name : 'Fathima',
Last_Name : 'Sheik',
Date_Of_Birth: '1990-02-16',
e_mail: 'fathima_sheik.123@gmail.com',
phone: '9000012345'
}
];
// make a connection to the database
MongoClient.connect(url, function(error, client) {
if (error) throw error;
console.log("Connected!");
// Connect to the database
const database = client.db('myDb');
database.collection("sampleCollection").insertOne(firstDocument, function(error, res) {
if (error) throw error;
console.log("1 document inserted");
});
database.collection("sampleCollection").insertMany(documents, function(error, res) {
if (error) throw error;
console.log("Documents inserted: " + res.insertedCount);
});
// close the connection
client.close();
});
输出
使用 Node 执行 mysql_example.js 脚本并验证输出。
node mongodb_example.js Documents inserted: 3 1 document inserted