다음 예시는 Atlas Data API에 요청을 보내는 방법을 보여줍니다.
생성, 읽기, 업데이트. 삭제(CRUD) 작업
다음 예시는 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 types 지정
데이터 API 요청은 요청 본문에서 EJSON 데이터 형식을 대신 사용해 JSON에 존재하지 않는 BSON 유형을 지정할 수 있습니다. EJSON을 사용해 쿼리 필터에서 BSON types를 일치시키거나 삽입 작업과 업데이트 작업에서 BSON types를 작성할 수 있습니다.
요청 본문에서 EJSON을 사용하도록 지정하려면 Content-Type
헤더를 설정합니다.
Content-Type: application/ejson
바이너리
바이너리 값을 지정하려면 $binary
Base 로 인코딩된 값과 함께 을 사용하고64 2자 16진수문자열로 인코딩된 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
객체를 사용합니다. 이 값은 사용하려는 EJSON 형식에 따라 달라집니다.
캐노니컬 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(객체 ID) 값을 지정하려면 해당 ID와 함께 $oid
을(를) 다음과 같이 바이트 문자열로 사용하세요.
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 값입니다. EJSON $oid
객체를 사용하는 문서를 포함해 모든 ObjectID 필드를 일치시킬 수 있습니다.
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" } } } }'
데이터 액세스 권한
앱의 기본 제공 역할 기반 권한을 사용하여 데이터 API 요청을 보호할 수 있습니다. 이 섹션의 예시에서는 일반적인 권한 체계를 설정하는 방법을 보여줍니다. API의 요구 사항을 충족하도록 이러한 체계와 더 복잡한 체계를 혼합하여 사용할 수 있습니다. 권한의 실행 방식에 대한 기타 예시 및 자세한 내용은 Role-based Permissions(역할 기반 권한)를 참조하세요.
특정 API 키에 대한 권한 정의
서로 다른 데이터 액세스 권한을 가진 다양한 역할을 정의하고 각 역할에 특정 API 키를 할당할 수 있습니다. 예를 들어, 사용자가 모든 데이터를 읽을 수 있지만 데이터를 삽입하거나, 삭제하거나, 수정할 수는 없도록 하는 read-only
역할을 생성할 수 있습니다.
각 역할을 역할의 apply_when
표현식에 있는 API 키에 매핑합니다.
각 API 키는 고유한 계정 ID를 가진 별도의 사용자 계정에 해당합니다. %%user
확장을 사용하여 요청하는 사용자의 계정 ID 및 기타 데이터에 액세스할 수 있습니다.
역할을 단일 API 키에 연결하려면 해당 API 키의 계정 ID와 일치하도록 apply_when
표현식을 설정하세요.
{ "database": "<database>", "collection": "<collection>", "roles": [ { "name": "SpecificUser", "apply_when": { "%%user.id": "61f9a5e69cd3c0199dc1bb88" }, "insert": true, "delete": true, "read": true, "write": true } ], "filters": [] }
역할을 여러 API 키와 연결하려면 API 키 계정 ID 배열과 일치하도록 apply_when
표현식을 설정하세요.
{ "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": [] }
이 예시에서는 사용자 지정 사용자 데이터 컬렉션을 사용하지만 다른 외부 서비스를 사용해서도 사용자에게 역할이 있는지 확인할 수 있습니다. 전달할 함수 코드와 인수는 원하는 대로 결정할 수 있습니다.
특정 collection에 대한 권한 정의하기
클러스터의 특정 컬렉션에 대한 데이터 액세스 권한을 제어하는 역할을 정의할 수 있습니다. 예를 들어 사용자가 컬렉션의 모든 데이터를 읽을 수는 있지만 데이터를 삽입, 삭제 또는 수정할 수는 없는 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": [] }