0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongoLab の REST API でドキュメントの検索削除方法が特殊だったのでメモ

0
Last updated at Posted at 2015-04-21

MongoLabREST API をPHPから利用してて、ドキュメントの削除で、検索してマッチしたもの(例えば指定日時より古いもの全部とか)を削除したいんだけど、一筋縄ではいかなかったのでメモ。
(自サーバーインストール型の普通のMongoDBとは違うかもしれないのでご注意を)

最初に試したのは以下のようなプログラム

失敗例その1
$query = array(
    'date' => array(
        '$lt' => '20xx-xx-xx xx:xx:xx' // この日時より古いものを削除したい
    )
);
$url = 'https://api.mongolab.com/api/1/databases/[db名]/collections/[collection名]';
$url .= '?apiKey=[APIキー]';
$url .= '&q='.urlencode(json_encode($query));

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$res = curl_exec($ch);
curl_close($ch);

これだと「DELETE not allowed.」というメッセージが返ってきた。
ちなみにドキュメントの_idがわかってて、1件だけ削除する場合は以下(DELETEメソッド)で問題ない。

$url = 'https://api.mongolab.com/api/1/databases/[db名]/collections/[collection名]/[_id値]';
$url .= '?apiKey=[APIキー]';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
curl_close($ch);

DELETEのリファレンスを読んだところ、どうやら検索しつつ削除する場合はPUTメソッドでないといけないっぽい感じなので、以下を試してみた。

失敗例その2
$query = array(
    'date' => array(
        '$lt' => '20xx-xx-xx xx:xx:xx'
    )
);
$url = 'https://api.mongolab.com/api/1/databases/[db名]/collections/[collection名]';
$url .= '?apiKey=[APIキー]';
$url .= '&q='.urlencode(json_encode($query));

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // ここをPUTにしただけ
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
curl_close($ch);

これだと、なぜか全ドキュメントが消えてしまった。
たぶんPUTしてるのにデータがゼロなので「データなし」で上書きしたっぽい?よくわからない。

結局いろいろと試して、どうやらPOSTでなんらかのデータは送らないといけないようだったので、最終的に以下のような形になった。

成功例
$query = array(
    'date' => array(
        '$lt' => '20xx-xx-xx xx:xx:xx'
    )
);
$url = 'https://api.mongolab.com/api/1/databases/[db名]/collections/[collection名]';
$url .= '?apiKey=[APIキー]';
$url .= '&q='.urlencode(json_encode($query));

$data = json_encode(array());// 空のデータを送る必要がある
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: '.strlen($data)
));
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
curl_close($ch);

なんだか腑に落ちない仕様だった・・・

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?