- 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——选择文档
- Node & MongoDB——更新文档
- Node & MongoDB——删除文档
- Node & MongoDB——嵌入式文档
- Node & MongoDB——限制记录
- Node & MongoDB——对记录排序
- Node & MongoDB 有用资源
- Node & MongoDB——快速指南
- Node & MongoDB——有用资源
- Node & MongoDB——讨论
节点和 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://:27017/";
const firstPost = {
title : 'MongoDB Overview',
description : 'MongoDB is no SQL database',
by: 'tutorials point',
url: 'https://tutorialspoint.com',
comments: [{
user: 'user1',
message: 'My First Comment',
dateCreated: '20/2/2020',
like: 0
},
{
user: 'user2',
message: 'My Second Comment',
dateCreated: '20/2/2020',
like: 0
}]
};
// 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('posts');
database.collection("samplePost").insertOne(firstPost, function(error, res) {
if (error) throw error;
console.log("1 document inserted");
});
// close the connection
client.close();
});
输出
使用 node 执行 mysql_example.js 脚本,并验证输出。
node mongodb_example.js Connected. 1 document inserted
广告