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;
// 准备 URL
const url = "mongodb://localhost:27017/";
// 建立与数据库的连接
MongoClient.connect(url, function(error, client) {
if (error) throw error;
console.log("Connected!");
// 连接数据库
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);
});
// 关闭连接
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'
}
]

