Usage Examples用法示例¶
Overview概述¶
Usage examples provide convenient starting points for popular MongoDB operations. 使用示例为流行的MongoDB操作提供了方便的起点。Each example provides:每个示例提供:
an explanation of the operation in the example showing the purpose and a sample use case for the method示例中的操作说明,说明了该方法的用途和示例用例an explanation of how to use the operation, including parameters, return values, and common exceptions you might encounter说明如何使用该操作,包括参数、返回值和可能遇到的常见异常a full Node.js program that you can copy and paste to run the example in your own environment一个完整的Node.js程序,您可以复制并粘贴该程序,以便在自己的环境中运行该示例
How to Use the Usage Examples如何使用用法示例¶
These examples use the MongoDB Atlas sample data database. 这些示例使用MongoDB Atlas示例数据数据库。You can use this sample data on the free tier of MongoDB Atlas by following the Get Started with Atlas guide or you can import the sample dataset into a local MongoDB instance.您可以按照Atlas入门指南在MongoDB Atlas的免费层上使用此示例数据,也可以将示例数据集导入本地MongoDB实例。
Once you have imported the dataset, you can copy and paste a usage example into your development environment of choice. 导入数据集后,可以将使用示例复制并粘贴到所选的开发环境中。You can follow the quick start guide to learn more about getting started with Node.js, npm, and the Node.js driver. 您可以按照快速入门指南了解更多有关Node.js、npm和Node.js驱动程序的入门信息。Once you've copied a usage example, you'll have to edit one line to get the example running with your instance of MongoDB:复制使用示例后,您必须编辑一行以使示例与您的MongoDB实例一起运行:
// Replace the following with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换以下内容。
const uri =
"mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
All examples use ES module imports. 所有示例都使用ES模块导入。You can enable ES module imports by adding the following key-value pair to your package.json file:您可以通过向package.json文件添加以下键值对来启用ES模块导入:
"type": "module"
You can use any usage example with CommonJS 您可以使用CommonJSrequire
. require
任何用法示例。To use CommonJS 要使用CommonJS require
, you must swap out the ES module import
statement for your CommonJS require
statement.require
,必须将ES模块import
语句替换为CommonJS require
语句。
Click on the tabs to see the syntax for importing the driver with ES module 单击选项卡以查看使用ES模块import
and CommonJS require
:import
和CommonJS require
导入驱动程序的语法:
import { MongoClient } from 'mongodb'
const { MongoClient } = require('mongodb')
You can use the Atlas Connectivity Guide to enable connectivity to your instance of Atlas and find the connection string to replace the 您可以使用Atlas Connectivity 指南启用到Atlas实例的连接,并在使用示例中查找连接字符串以替换uri变量。uri
variable in the usage example. If your instance uses SCRAM authentication, you can replace 如果您的实例使用紧急停堆身份验证,则可以使用您的用户名替换<user>
with your username, <password>
with your password, and <cluster-url>
with the IP address or URL of your instance. <user>
,使用您的密码替换<password>
,并使用实例的IP地址或URL替换<cluster-url>
。Consult the Connection Guide for more information about getting connected to your MongoDB instance.有关连接到MongoDB实例的更多信息,请参阅连接指南。