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://localhost: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
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}