以下示例演示了如何向 Atlas Data API 发送请求。
创建、读取、更新和删除(增删改查)操作
以下示例演示了如何使用 Atlas Data API 执行 CRUD 操作。
查找单个文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/findOne" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "text": "Do the dishes" } }'
查找多个文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/find" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "status": "complete" }, "sort": { "completedAt": 1 }, "limit": 10 }'
插入单一文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "document": { "status": "open", "text": "Do the dishes" } }'
插入多个文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertMany" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "documents": [ { "status": "open", "text": "Mop the floor" }, { "status": "open", "text": "Clean the windows" } ] }'
更新单份文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/updateOne" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "_id": { "$oid": "64224f4d089104f1766116a5" } }, "update": { "$set": { "status": "complete", "completedAt": { "$date": { "$numberLong": "1680105272788" } } } } }'
更新多个文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/updateMany" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "status": "open" }, "update": { "$set": { "status": "complete", "completedAt": { "$date": { "$numberLong": "1680105287069" } } } } }'
替换单份文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/replaceOne" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "text": "Clean the windows" }, "replacement": { "status": "open", "text": "Re-clean the windows" } }'
删除单个文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/deleteOne" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "_id": { "$oid": "64224f3cd79f54ad342dd9b2" } } }'
删除多个文档
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/deleteMany" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "status": "complete" } }'
运行聚合管道
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/aggregate" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "pipeline": [ { "$match": { "status": "complete" } }, { "$group": { "_id": "$status", "count": { "$sum": 1 }, "tasks": { "$push": "$text" } } }, { "$sort": { "count": -1 } } ] }'
在请求中指定 BSON 类型
数据 API 请求可以通过在请求正文中改用 EJSON 数据格式来指定在 JSON 中不存在的 BSON 类型。你可以使用 EJSON 来匹配查询筛选器中的 BSON 类型,或者在插入和更新操作中写入 BSON 类型。
要指定请求正文使用 EJSON,请设置Content-Type
标头:
Content-Type: application/ejson
二进制文件
要指定二进制值,请使用$binary
64以及以 Base 和编码为双字符十六进制字符串的 BSON类型 编码的值:
curl -s "https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne" \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "_id": { "$oid":"645404f4ee8583002fc5a77e" }, "data": { "$binary": { "base64": "46d989eaf0bde5258029534bc2dc2089", "subType": "05" } } } }'
Date
要指定日期,请使用 $date
对象。该值取决于要使用的 EJSON 格式。
Canonical EJSON
该值是以 64 位整数表示的 UNIX 时间戳(以毫秒为单位):
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "createdAt": { "$date": { "$numberLong": "1638551310749" } } } }'
宽松 EJSON
该值为带有时间组件的 ISO 8601 日期字符串:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "createdAt": { "$date": "2021-12-03T17:08:30.749Z" } } }'
Decimal128
要指定 128 位十进制,请使用 $numberDecimal
,接受十进制值作为字符串:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "accountBalance": { "$numberDecimal": "128452.420523" } } }'
double
要指定 64 位带符号浮点值(通常称为“double”),使用规范的 $numberDouble
,并将整数值作为字符串:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "temperatureCelsius": { "$numberDouble": "23.847" } } }'
宽松 EJSON
包含带小数点的原始 JSON number
的 EJSON 值会自动转换为 $numberDouble
对象:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "temperatureCelsius": 23.847 } }'
Int32
要指定 32 位带符号整数值,使用具有整数值的规范 $numberInt
对象作为字符串:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "coins": { "$numberInt": "2147483647" } } }'
宽松 EJSON
不含带小数点的原始 JSON number
的 EJSON 值会自动转换为 $numberInt
对象:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "coins": 2147483647 } }'
Int64
要指定 64 位有符号整数值,请使用 $numberLong
并将整数值作为字符串:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "population": { "$numberLong": "8047923148" } } }'
ObjectId
要指定对象标识符 (ObjectId) 值,使用 $oid
,并将 ID 作为字节字符串:
curl -s https://data.mongodb-api.com/app/$CLIENT_APP_ID/endpoint/data/v1/action/insertOne \ -X POST \ -H "apiKey: $API_KEY" \ -H 'Content-Type: application/ejson' \ -H "Accept: application/json" \ -d '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "_id": { "$oid": "61f02ea3af3561e283d06b91" } } }'
查询示例
本节中的代码片段演示了可在读取和写入操作中使用的常见模式。
查找所有文档
要匹配集合中的所有文档,请使用空的查询对象:
curl --request POST \ 'https://data.mongodb-api.com/app/<App ID>/endpoint/data/v1/action/find' \ --header 'Content-Type: application/ejson' \ --header 'apiKey: <API Key>' \ --data-raw '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "filter": {} }'
按 ID 查找文档
MongoDB 在 _id
字段中使用唯一标识符存储每个文档。对于大多数应用程序,这是一个 BSON ObjectID 值。您可以匹配任何 ObjectID 字段,包括使用 EJSON $oid
对象的文档:
curl --request POST \ 'https://data.mongodb-api.com/app/<App ID>/endpoint/data/v1/action/find' \ --header 'Content-Type: application/ejson' \ --header 'apiKey: <API Key>' \ --data-raw '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "filter": { "_id": { "$oid": "630e51b3f4cd7d9e606caab6" } } }'
按日期查找
您可以通过将 EJSON $date
对象与包含日期值的字段进行匹配来匹配特定日期的文档:
curl --request POST \ 'https://data.mongodb-api.com/app/<App ID>/endpoint/data/v1/action/find' \ --header 'Content-Type: application/ejson' \ --header 'apiKey: <API Key>' \ --data-raw '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "filter": { "createdAt": { "$date": "2022-08-30T17:52:05.033Z" } } }'
您可以用 $gt
、$gte
、$lt
和 $lte
查询一系列日期:
curl --request POST \ 'https://data.mongodb-api.com/app/<App ID>/endpoint/data/v1/action/find' \ --header 'Content-Type: application/ejson' \ --header 'apiKey: <API Key>' \ --data-raw '{ "dataSource": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "filter": { "createdAt": { "$gte": { "$date": "2022-01-01T00:00:00.000Z" }, "$lt": { "$date": "2023-01-01T00:00:00.000Z" } } } }'
数据访问权限
您可以使用应用基于角色的内置权限来保护 Data API 请求。本节中的示例演示如何设置常用权限方案。您可以混合和匹配这些以及更复杂的方案,以满足 API 的需求。有关权限工作原理的更多示例和信息,请参阅基于角色的权限。
为特定 API 密钥定义权限
您可以定义具有不同数据访问权限的多个角色,并为每个角色分配特定的 API 密钥。例如,可以创建一个read-only
角色,允许用户读取所有数据,但不能插入、删除或修改数据。
你可以在角色的 apply_when
表达式中将每个角色映射到 API 密钥。
每个 API 键对应一个具有唯一账户 ID 的单独用户账户。通过 %%user
扩展,可以访问提出请求的用户的账户 ID 和其他数据。
要将角色与单个 API 键关联,设置 apply_when
表达式以匹配 API 键的账户 ID:
{ "database": "<database>", "collection": "<collection>", "roles": [ { "name": "SpecificUser", "apply_when": { "%%user.id": "61f9a5e69cd3c0199dc1bb88" }, "insert": true, "delete": true, "read": true, "write": true } ], "filters": [] }
要将角色与多个 API 密钥关联,设置 apply_when
表达式以匹配一组 API 密钥帐户 ID:
{ "database": "<database>", "collection": "<collection>", "roles": [ { "name": "MultipleUsers", "apply_when": { "%%user.id": { "$in": [ "61f9a5e69cd3c0199dc1bb88", "61f9a5e69cd3c0199dc1bb89" ] } }, "insert": true, "delete": true, "read": true, "write": true } ], "filters": [] }
您还可以使用自定义系统来确定用户是否拥有某个角色。例如,您可以编写一个函数,从 Atlas 集群中查找用户的角色。
exports = async function hasRole({ userId, // The user account ID, e.g. "60d0c1bdee9d3c23b677f929" roleName, // The name of a role the user might have, e.g. "admin" }) { // 1. Get a reference to a custom user data collection const users = context.services.get("mongodb-atlas").db("app").collection("users") // 2. Query the user's document and make sure it exists const user = await users.findOne({ userId }) if(!user) { console.error(`User.id ${userId} not found in custom user data collection`) return false } // 3. Decide if the user has the role we're checking return user.roles.includes(roleName) };
然后,使用 %function
运算符从此角色的 apply_when
表达式调用该函数:
{ "database": "<database>", "collection": "<collection>", "roles": [ { "name": "SomeCustomRole", "apply_when": { "%%true": { "%function": { "name": "hasRole", "arguments": [{ "userId": "%%user.id", "roleName": "SomeCustomRole" }] } } }, "insert": true, "delete": true, "read": true, "write": true } ], "filters": [] }
此示例使用自定义用户数据集合,但您可以使用任意外部服务来确定用户是否拥有某个角色。您可自行决定传递的函数代码和参数。
为特定集合定义权限
您可以定义角色来控制集群中特定集合的数据访问权限。例如,可以创建一个read-only
角色,允许用户读取集合中的所有数据,但不能插入、删除或修改任何数据。
要为特定集合定义角色,请使用特定于集合的角色配置更新集合的配置文件:
{ "database": "<database>", "collection": "<collection>", "roles": [ { "name": "IsOwner", "apply_when": { "owner_id": "%%user.id" }, "insert": false, "delete": false, "read": true, "write": true } ], "filters": [] }
如果没有匹配的集合角色,则根据数据源的默认角色评估该请求。如果不想应用默认角色,则从默认规则配置文件中删除所有角色和筛选器。
{ "roles": [], "filters": [] }