- 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 - 討論
Node 與 MongoDB - 選擇文件
要選擇集合的文件,可以使用 collection.findOne() 或 collection.find() 方法選擇一個或多個文件。
database.collection("sampleCollection").findOne({}, function(error, result) {
if (error) throw error;
console.log(result);
});
database.collection("sampleCollection").find({}).toArray(function(error, result) {
if (error) throw error;
console.log(result);
});
示例
嘗試以下示例來在 mongodb 集合中選擇文件 −
將以下示例複製並貼上為 mongodb_example.js −
const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://:27017/";
// 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").findOne({}, function(error, result) {
if (error) throw error;
console.log(result);
}); database.collection("sampleCollection").find({}).toArray(function(error, result) {
if (error) throw error;
console.log(result);
});
// close the connection
client.close();
});
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js
Connected!
{
_id: 60c4bbb40f8c3920a0e30fdd,
First_Name: 'Radhika',
Last_Name: 'Sharma',
Date_Of_Birth: '1995-09-26',
e_mail: 'radhika_sharma.123@gmail.com',
phone: '9000012345'
}
[
{
_id: 60c4bbb40f8c3920a0e30fdd,
First_Name: 'Radhika',
Last_Name: 'Sharma',
Date_Of_Birth: '1995-09-26',
e_mail: 'radhika_sharma.123@gmail.com',
phone: '9000012345'
},
{
_id: 60c4bbb40f8c3920a0e30fde,
First_Name: 'Rachel',
Last_Name: 'Christopher',
Date_Of_Birth: '1990-02-16',
e_mail: 'rachel_christopher.123@gmail.com',
phone: '9000054321'
},
{
_id: 60c4bbb40f8c3920a0e30fdf,
First_Name: 'Fathima',
Last_Name: 'Sheik',
Date_Of_Birth: '1990-02-16',
e_mail: 'fathima_sheik.123@gmail.com',
phone: '9000012345'
},
{
_id: 60c4bbb40f8c3920a0e30fdc,
First_Name: 'Mahesh',
Last_Name: 'Parashar',
Date_Of_Birth: '1990-08-21',
e_mail: 'mahesh_parashar.123@gmail.com',
phone: '9034343345'
}
]
廣告