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 3 years have passed since last update.

MongoDBのgolang-migrateでdate型のデータを登録したい場合

0
Posted at

概要

golang-migrateでMongoDBのマイグレーションの記事にある通り、golang-migrateではMongoDBのマイグレーションが可能です。マイグレーションファイルでは、ドキュメントの更新も行えるのですが、今回date型のデータを登録したい場合、どうするかというのをまとめます。

対応

How to insert date into mongo from JSON fileの記事にある通り、 "createdAt": { "$date": "2018-11-10T22:26:12.111Z" }のような形式でマイグレーションファイルを用意すれば日付型を登録できると思ったのですが、golang-migrateでは実行時にエラーになりました。
こちらのIssueにある通り、golang-migrateでは日付型への変換はサポートしていないそうです・・。代替案としてcurrentDateを使ったupdateが紹介されています。つまり、一度データをinsertした後に、現在日付でupdateするということなら実現可能になります。

設定サンプル

上記のIssueで紹介されている内容ほぼそのままですが、現在日付で設定するサンプルを紹介します。
一度日付をnullで登録した後に現在日付でupdateします。

001_create_sample_user.up.json
[
 {
    "insert": "sample_user",
    "documents": [
      {
        "_id": "id1",
        "name": "user1",
        "created_date": null
      }
    ]
  },
 {
    "insert": "sample_user",
    "documents": [
      {
        "_id": "id2",
        "name": "user2",
        "created_date": null
      }
    ]
  },
  {
    "update": "sample_user",
    "updates": [
      {
        "q": { "created_date": null },
        "u": {
          "$currentDate": {
            "created_date": true
          }
        },
        "multi": true
      }
    ]
  }
]
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?