findOne()方法用于从MongoDB中的集合中选择单个数据。此方法返回集合的第一条记录。
例子
(选择单条记录)
从”员工”中选择第一条记录。采集。
创建一个名为” select.js”的js文件, 其代码如下:
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MongoDatabase";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("employees").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});
打开命令终端并运行以下命令:
Node select.js

选择多个记录
find()方法用于从MongoDB中的集合中选择所有记录。
例子
从”员工”集合中选择所有记录。
创建一个名为” selectall.js”的js文件, 其代码如下:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MongoDatabase";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("employees").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
打开命令终端并运行以下命令:
Node selectall.js

你可以看到所有记录都已检索。
来源:
https://www.srcmini02.com/27888.html