对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

快速参考

本页显示了若干 MongoDB 命令的驱动程序语法,以及指向相关引用和 API 文档的链接。

您可以使用 Node.js 驱动程序连接到以下环境中托管的部署并对其执行命令:

要详细了解如何在 Atlas 用户界面中为 MongoDB Atlas 中托管的部署执行常见的 CRUD 操作,请参阅创建、查看、更新和删除文档

命令
语法
await coll.findOne({ title: 'Hamlet' });
coll.find({ year: 2005 });
await coll.insertOne({ title: 'Jackie Robinson' });
await coll.insertMany([
{ title: 'Dangal', rating: 'Not Rated' },
{ title: 'The Boss Baby', rating: 'PG' }
]);
await coll.updateOne(
{ title: 'Amadeus' },
{ $set: { 'imdb.rating': 9.5 } }
);
await coll.updateMany(
{ year: 2001 },
{ $inc: { 'imdb.votes': 100 } }
);
await coll.updateOne(
{ title: 'Cosmos' },
{ $push: { genres: 'Educational' } }
):
await coll.replaceOne(
{ name: 'Deli Llama', address: '2 Nassau St' },
{ name: 'Lord of the Wings', zipcode: 10001 }
);
await coll.deleteOne({ title: 'Congo' });
await coll.deleteMany({ title: { $regex: /^Shark.*/ } });
await coll.bulkWrite([
{
insertOne: {
document: {
title: 'A New Movie',
year: 2022
}
}
},
{
deleteMany: {
filter: { year: { $lt: 1970 } }
}
}
]);
coll.watch([ { $match: { year: { $gte: 2022 } } } ]);

从游标迭代访问数据

从游标访问数据指南

const cursor = coll.find();
for await (const doc of cursor) {
console.dir(doc);
}

以数组形式访问游标中的数据

API 文档
从游标访问数据指南

const cursor = coll.find();
const results = await cursor.toArray();
await coll.countDocuments({ year: 2000 });

列出不同的文档或字段值
API 文档
Retrieve Distinct Values Guide

await coll.distinct('year');

限制检索的文档数量

API 文档
限制文档参考

coll.find().limit(2);

跳过检索到的文档

API 文档
跳过文档引用

coll.find({ title: { $regex: /^Rocky/} }, { skip: 2 });

检索文档时对文档进行排序

API 文档
对文档参考进行排序

coll.find().sort({ year: 1});

检索项目文档字段时

API 文档
指定要返回的字段指南

coll.find().project({ _id: 0, year: 1, imdb: 1 });
await coll.createIndex({ title: 1, year: -1 });
// only searches fields with text indexes
coll.find({ $text: { $search: 'zissou' } });

安装驱动程序依赖项

package.json
"dependencies": {
"mongodb": "^6.21",
...
}
给本页内容打分