• Node.js Video Tutorials

Node.js - MongoDB 插入



MongoDB是一個面向文件的資料庫,可以透過名為mongodb的NPM模組與Node.js互動。文件是MongoDB資料庫的核心。它是一組鍵值對的集合。我們也可以將其視為類似於SQL基於關係資料庫的表中的一行,就像MongoDB中的集合類似於關係資料庫中的表一樣。NPM mongodb包提供了insertOne()和insertMany()方法,可以使用這些方法將一個或多個文件從Node.js應用程式新增到集合中。

MongoDB將資料記錄儲存為BSON文件。BSON是JSON文件的二進位制表示。MongoDB文件由欄位和值對組成,具有以下結構:

{
   field1: value1,
   field2: value2,
   field3: value3,
   ...
   fieldN: valueN
}

欄位的值可以是任何BSON資料型別,包括其他文件、陣列和文件陣列。

每個文件都以一個名為“_id”的特殊鍵為特徵,該鍵具有唯一值,類似於關係資料庫實體表中的主鍵。鍵也稱為欄位。如果插入的文件省略了_id欄位,則MongoDB驅動程式會自動為_id欄位生成一個ObjectId。

insertOne() 方法

Collection物件具有insertOne()方法,該方法將單個文件插入到集合中。

Collection.insertOne(doc)

要插入的文件作為引數傳遞。它將單個文件插入到MongoDB中。如果傳入的文件不包含_id欄位,驅動程式將向每個缺少該欄位的文件新增一個_id欄位,從而修改文件。

示例

使用以下程式碼,我們將單個文件插入資料庫中的products集合中。

const {MongoClient} = require('mongodb');

async function main(){
   const uri = "mongodb://:27017";
   const client = new MongoClient(uri);

   try {
      // Connect to the MongoDB cluster
      await client.connect();

      // Make the appropriate DB calls

      // Create a single new document
      await createdoc(client, "mydatabase", "products", {
         "ProductID":1, "Name":"Laptop", "Price":25000
      });
  
       
   } finally {
      // Close the connection to the MongoDB cluster
      await client.close();
   }
}

main().catch(console.error);

async function createdoc(client, dbname, colname, doc){
   const dbobj = await client.db(dbname);
   const col = dbobj.collection(colname);
   const result = await col.insertOne(doc);
   console.log(`New document created with the following id: ${result.insertedId}`);
}

輸出

建立新的列表,ID為:65809214693bd4622484dce3

Mydp Products

Mongo shell也可以用來檢視插入的文件。

> use mydb;
< switched to db mydb
> products=db['products']
< mydb.products
> docs=products.find()
{
   _id: ObjectId("65809214693bd4622484dce3"),
   ProductID: 1,
   Name: 'Laptop',
   Price: 25000
}

insertMany() 方法

Collection物件的insertMany()方法使得可以插入多個文件。JSON文件陣列用作引數。我們還在下面的示例中使用了SRV連線字串:

示例

const {MongoClient} = require('mongodb');

async function main(){

   //const uri = "mongodb://:27017";
   const uri = "mongodb+srv://user:mypwd@cluster0.zhmrg1h.mongodb.net/?retryWrites=true&w=majority";
   
   const client = new MongoClient(uri);

   try {
      // Connect to the MongoDB cluster
      await client.connect();

      // Make the appropriate DB calls

      // insert documents
      await createdocs(client, [
         {'ProductID':1, 'Name':'Laptop', 'price':25000},
         {'ProductID':2, 'Name':'TV', 'price':40000},
         {'ProductID':3, 'Name':'Router', 'price':2000},
         {'ProductID':4, 'Name':'Scanner', 'price':5000},
         {'ProductID':5, 'Name':'Printer', 'price':9000}
      ]);
  
   } finally {
      // Close the connection to the MongoDB cluster
      await client.close();
   }
}

main().catch(console.error);

async function createdocs(client, docs){
   const result = await client.db("mydb").collection("products").insertMany(docs);
   console.log(`${result.insertedCount} new document(s) created with the following id(s):`);
   console.log(result.insertedIds);
}

輸出

5 new listing(s) created with the following id(s):
{
   '0': new ObjectId('6580964f20f979d2e9a72ae7'),
   '1': new ObjectId('6580964f20f979d2e9a72ae8'),
   '2': new ObjectId('6580964f20f979d2e9a72ae9'),
   '3': new ObjectId('6580964f20f979d2e9a72aea'),
   '4': new ObjectId('6580964f20f979d2e9a72aeb')
}

您可以將文件集合匯出為CSV格式。

_id,ProductID,Name,Price,price
65809214693bd4622484dce3,1,Laptop,25000,
6580964f20f979d2e9a72ae8,2,TV,40000
6580964f20f979d2e9a72ae9,3,Router,2000
6580964f20f979d2e9a72aea,4,Scanner,5000
6580964f20f979d2e9a72aeb,5,Printer,9000
廣告