LoginSignup
0
0

More than 1 year has passed since last update.

【Go】mongo-go-driverでコレクションの全件を取得する

Posted at

概要

MongoDBで全件検索したい時、[Mongo] findメソッドのいろいろな使い方(MySQLと比較)の記事にある通り単純にfindメソッドを使えばOKです。では、GolangでMongoDBを使用する際に使う、mongo-go-driverで全件取得するにはどうすれば良いのか。
[Mongo] findメソッドのいろいろな使い方(MySQLと比較)の記事を見ると、FindメソッドはFind(context.Context, 検索条件, Find オプション)とあり、検索条件の部分はnilを設定すれば良いのかなと思いnilを設定したところ、エラーとなりました。

対応

こちらのドキュメントを読むと、
The filter parameter must be a document containing query operators and can be used to select which documents are included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include all documents.
とある通り、検索条件にはnilは許可されておらず空のドキュメントを設定する必要があるとのこと。
ちなみに、nilを設定するとs: "document is nil"という不親切なエラーが発生します。

ドキュメントをちゃんと読めば気づけたのですが、この記述に気付かずエラーの原因を探すのに手間取ったので、今回記事にしました。。

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