
- 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.tw', 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
廣告