LoginSignup
8
7

More than 5 years have passed since last update.

Mongo シェルから他言語から読めるJSONを出力する

Last updated at Posted at 2016-06-07

jsonなのに、他言語から読めないとかおまえ何いってんだ、と思うかもしれないが、mongoのシェル内でオブジェクトを評価すると

> db.test.find()
{ "_id" : ObjectId("5756c7f021baef6e3efc34c2"), "date" : ISODate("2016-06-07T13:11:12.690Z") }

のような出力になる。

printjson という素敵な組み込み関数があるが、その結果がこう

> printjson(db.test.find().toArray())
[
        {
                "_id" : ObjectId("5756c7f021baef6e3efc34c2"),
                "date" : ISODate("2016-06-07T13:11:12.690Z")
        }
]

ObjectId ,ISODate というのは、mongoのシェル内でコピペとかするにはそのまま使えてよろしいんだけど、 json としてはそのまま使えない。

そういう時は、

> ObjectId.prototype.tojson = function() { return '"' + this.valueOf() + '"'; };
> Date.prototype.tojson = function() { return '"' + this.toISOString() + '"'; };

としておくと、結果を普通のjsonにできる、という小技でした。

> printjson(db.test.find().toArray())
[
        {
                "_id" : "5756c7f021baef6e3efc34c2",
                "date" : "2016-06-07T13:11:12.690Z"
        }
]
8
7
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
8
7