データ API の例
項目一覧
次の例は、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 types を指定できます。EJSON を使用して、クエリ フィルターで BSON types を照合したり、挿入操作と更新操作で BSON types を書き込んだりできます。
リクエスト本文での EJSON 使用を指定するには、 Content-Type
ヘッダーを設定します。
Content-Type: application/ejson
バイナリ
$binary
バイナリ値を指定するには、Base でエンコードされた値と64 BSON サブタイプ でエンコードされた値を持つ を使用します。 2 文字の 16 進 string としてエンコードされた場合
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
値は、時間要素を含む ISO8601 日付文字列です。
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 ビットの 10 進数を指定するには、$numberDecimal
と 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": "<cluster name>", "database": "<database name>", "collection": "<collection name>", "document": { "accountBalance": { "$numberDecimal": "128452.420523" } } }'
Double
64 ビットの符号付き浮動小数点値(一般に「double」と呼ばれる)を指定するには、整数値を string とする標準 $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 をバイト文字列として指定した$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 のニーズに合わせて、これらのスキームとより複雑なスキームを組み合わせることができます。権限の仕組みに関するその他の例と情報については、ロールベースの権限を参照してください。
特定の 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": [] }
カスタム システムを使用して、ユーザーにロールがあるかどうかを判断することもできます。たとえば、MongoDB 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": [] }