LoginSignup
16
14

More than 5 years have passed since last update.

MongoDBのREST APIの挙動について

Last updated at Posted at 2014-10-22

MongoDB HTTP Interfaceにある通り、mongod--restオプション付きで起動するとRESTful HTTP APIを提供する。

これは便利なはず・・・なのだが、予想と動きが違う。

試しに--restオプションをつけて起動。

# cp -p /etc/mongod.conf /etc/mongod.conf.orig
# vim /etc/mongod.conf
+rest=true
# service mongod start

何件かデータを投入したコレクションを作る。

> use test_db
> db.test_coll.insert({"test_key":"alpha"})
> db.test_coll.insert({"test_key":"2014"})
> db.test_coll.insert({"test_key":"beta2014"})
> db.test_coll.insert({"test_key":"2014gamma"})
> db.test_coll.insert({"test_key":2015})

REST APIをcurlでcallしてみる。

$ curl localhost:28017/test_db/test_coll/
{
  "offset" : 0,
  "rows": [
    { "_id" : { "$oid" : "5447b0c4baa91c44440ade8a" }, "test_key" : "alpha" } ,
    { "_id" : { "$oid" : "5447b0d6baa91c44440ade8b" }, "test_key" : "2014" } ,
    { "_id" : { "$oid" : "5447b0e4baa91c44440ade8c" }, "test_key" : "beta2014" } ,
    { "_id" : { "$oid" : "5447b0edbaa91c44440ade8d" }, "test_key" : "2014gamma" } ,
    { "_id" : { "$oid" : "5447b279465a49b060dd2d0a" }, "test_key" : 2015 }
  ],

  "total_rows" : 5 ,
  "query" : {} ,
  "millis" : 0
}

1,3,5つめの例はキー指定でマッチする。

$ curl localhost:28017/test_db/test_coll/?filter_test_key=alpha
{
  "offset" : 0,
  "rows": [
    { "_id" : { "$oid" : "544772746f8c26500950b3ad" }, "test_key" : "alpha" }
  ],

  "total_rows" : 1 ,
  "query" : { "test_key" : "alpha" } ,
  "millis" : 0
}

$ curl localhost:28017/test_db/test_coll/?filter_test_key=beta2014
{
  "offset" : 0,
  "rows": [
    { "_id" : { "$oid" : "5447b0e4baa91c44440ade8c" }, "test_key" : "beta2014" }
  ],

  "total_rows" : 1 ,
  "query" : { "test_key" : "beta2014" } ,
  "millis" : 0
}

$ curl localhost:28017/test_db/test_coll/?filter_test_key=2015
{
  "offset" : 0,
  "rows": [
    { "_id" : { "$oid" : "5447b279465a49b060dd2d0a" }, "test_key" : 2015 }
  ],

  "total_rows" : 1 ,
  "query" : { "test_key" : 2015 } ,
  "millis" : 0
}

2,4つめの例はマッチしない。

$ curl localhost:28017/test_db/test_coll/?filter_test_key=2014
{
  "offset" : 0,
  "rows": [

  ],

  "total_rows" : 0 ,
  "query" : { "test_key" : 2014 } ,
  "millis" : 0
}

$ curl localhost:28017/test_db/test_coll/?filter_test_key=2014gamma
{
  "offset" : 0,
  "rows": [

  ],

  "total_rows" : 0 ,
  "query" : { "test_key" : 2014 } ,
  "millis" : 0
}

queryをよくみると、2つめではクエリのキーが数値と解釈され、文字列を含むdocumentがマッチしない。さらに4つめでは2014gammaが途中で切れて2014となっている。

How do I query for a string in MongoDB's Simple REST interface? - stackoverflow
によると、パラメータが数値かどうかをREST APIが判断するロジックがやや不十分なようにみえるが、MongoDB内で区別できる型がHTTPリクエストでは指定されていないので仕方ないとも考えられる。

最新の2.6.5でも現象を確認できた。注意を要する。

追記

更新、認証などは動作保証がないので、productionで使うのは非推奨、とのこと。
http://docs.mongodb.org/manual/core/security-interface/#rest-api

16
14
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
16
14