在本章中,我们将深入探讨如何使用 MongoDB 的数据 API 来执行常见的数据库操作。MongoDB 是一个功能强大的文档型数据库系统,它允许开发者高效地存储和检索数据。通过学习 MongoDB 的数据 API,你可以更好地利用其丰富的功能来满足你的应用需求。
安装 MongoDB 驱动
在开始之前,你需要确保已经安装了 MongoDB 的驱动程序。对于 Node.js 开发者来说,这通常意味着安装 mongodb 包。你可以通过 npm 来安装:
npm install mongodb
安装完成后,你可以通过以下代码来连接到 MongoDB 数据库:
// www.javascriptcn.com code example
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Connected to the database!");
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);请替换 <username> 和 <password> 为你的实际用户名和密码。
插入数据
插入单个文档
你可以使用 insertOne() 方法来插入一个文档。下面的示例展示了如何向集合中添加一个新的文档:
async function insertDocument(client, doc) {
const result = await client.db("test").collection("documents").insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
}
// 使用示例
const myDoc = { name: "John", age: 30 };
await insertDocument(client, myDoc);插入多个文档
如果你需要一次插入多个文档,可以使用 insertMany() 方法。这个方法接受一个数组作为参数,并将所有文档插入到指定的集合中:
// www.javascriptcn.com code example
async function insertMultipleDocuments(client, docs) {
const result = await client.db("test").collection("documents").insertMany(docs);
console.log(`${result.insertedCount} documents were inserted`);
}
// 使用示例
const multipleDocs = [
{ name: "Jane", age: 25 },
{ name: "Emily", age: 35 }
];
await insertMultipleDocuments(client, multipleDocs);查询数据
简单查询
你可以使用 find() 方法来查询集合中的文档。这个方法返回一个游标,你可以遍历它来获取结果:
async function findDocuments(client) {
const cursor = await client.db("test").collection("documents").find({});
await cursor.forEach(doc => console.log(doc));
}
// 使用示例
await findDocuments(client);条件查询
更复杂的查询可以通过传递一个查询条件对象给 find() 方法来实现。例如,只选择年龄大于 30 的文档:
async function findDocumentsByCondition(client) {
const cursor = await client.db("test").collection("documents").find({ age: { $gt: 30 } });
await cursor.forEach(doc => console.log(doc));
}
// 使用示例
await findDocumentsByCondition(client);更新数据
更新单个文档
使用 updateOne() 方法可以更新匹配条件的第一个文档:
// www.javascriptcn.com code example
async function updateDocument(client) {
const filter = { name: "John" };
const updateDoc = {
$set: {
age: 31
}
};
const result = await client.db("test").collection("documents").updateOne(filter, updateDoc);
console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
}
// 使用示例
await updateDocument(client);更新多个文档
如果想更新符合相同条件的所有文档,可以使用 updateMany() 方法:
// www.javascriptcn.com code example
async function updateMultipleDocuments(client) {
const filter = { age: { $lt: 40 } };
const updateDoc = {
$set: {
status: "active"
}
};
const result = await client.db("test").collection("documents").updateMany(filter, updateDoc);
console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
}
// 使用示例
await updateMultipleDocuments(client);删除数据
删除单个文档
使用 deleteOne() 方法删除匹配条件的第一个文档:
async function deleteDocument(client) {
const filter = { name: "John" };
const result = await client.db("test").collection("documents").deleteOne(filter);
console.log(`${result.deletedCount} document(s) deleted`);
}
// 使用示例
await deleteDocument(client);删除多个文档
如果想删除符合相同条件的所有文档,可以使用 deleteMany() 方法:
async function deleteMultipleDocuments(client) {
const filter = { age: { $lt: 30 } };
const result = await client.db("test").collection("documents").deleteMany(filter);
console.log(`${result.deletedCount} document(s) deleted`);
}
// 使用示例
await deleteMultipleDocuments(client);以上就是 MongoDB 数据 API 的基本操作。通过这些基础操作,你可以开始构建自己的数据库应用程序,并利用 MongoDB 提供的强大功能来处理各种数据需求。