• Node.js Video Tutorials

Node.js - MongoDB 查詢



MongoShell 客戶端類似於 MySQL 命令列工具。它是一個與 MongoDB 資料庫互動的工具。您可以使用 MongoDB 語言執行 CRUD 操作。MongoDB 語言類似於 SQL。Collection 物件可用的 find() 和 findOne() 方法相當於 SQL 中的 SELECT 查詢。這些方法也在 mongodb 模組中定義,以便與 Node.js 應用程式一起使用。

find() 方法有一個引數,引數形式為 JSON 格式的查詢。

db.collection.find({k:v});

find() 方法返回一個結果集,該結果集包含滿足給定查詢的集合中的所有文件。如果查詢引數為空,則返回集合中的所有文件。

讀取所有文件

以下示例檢索 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 listing
      await listall(client, "mydb", "products");
   } finally {
      // Close the connection to the MongoDB cluster
      await client.close();
   }
}
main().catch(console.error);


async function listall(client, dbname, colname){
   const result = await client.db("mydb").collection("products").find({}).toArray();
   console.log(JSON.stringify(result));
}

輸出

[{"_id":"65809214693bd4622484dce3","ProductID":1,"Name":"Laptop","Price":25000},{"_id":"6580964f20f979d2e9a72ae7","ProductID":1,"Name":"Laptop","price":25000},{"_id":"6580964f20f979d2e9a72ae8","ProductID":2,"Name":"TV","price":40000},{"_id":"6580964f20f979d2e9a72ae9","ProductID":3,"Name":"Router","price":2000},{"_id":"6580964f20f979d2e9a72aea","ProductID":4,"Name":"Scanner","price":5000},{"_id":"6580964f20f979d2e9a72aeb","ProductID":5,"Name":"Printer","price":9000}]

您還可以使用 forEach 迴圈遍歷結果集,如下所示:

var count=0;
result.forEach(row => {
   count++;
   console.log(count, row['Name'], row['price']);
});

輸出

1 Desktop 20000
2 Laptop 25000
3 TV 40000
4 Router 2000
5 Scanner 5000
6 Printer 9000

findOne()

findOne() 方法返回給定查詢的第一個匹配項。以下程式碼返回名稱為 TV 的產品的文件

async function listall(client, dbname, colname){
   const result = await client.db(dbname).collection(colname).find({"Name":"TV"}).toArray();
   console.log(JSON.stringify(result));
}

輸出

[{"_id":"6580964f20f979d2e9a72ae8","ProductID":2,"Name":"TV","price":40000}]

如果查詢為空,則返回集合中的第一個文件。

async function listall(client, dbname, colname){
   const result = await client.db(dbname).collection(colname).findOne({});
   console.log(JSON.stringify(result));
}

輸出

{"_id":"65809214693bd4622484dce3","ProductID":1,"Name":"Laptop","Price":25000}
廣告