LoginSignup
6
6

More than 5 years have passed since last update.

mongoでfind-limitを使った際のcountについて

Posted at

一瞬「なんで!?」ってなるからメモ。

console
> db.sorich.find({ "admin_user_id" : 2})
{ "_id" : ObjectId("******001"), "hoge_id" : 1, "satousan" : 2 }
{ "_id" : ObjectId("******002"), "hoge_id" : 2, "satousan" : 2 }
{ "_id" : ObjectId("******003"), "hoge_id" : 3, "satousan" : 2 }
> db.sorich.find({ "satousan" : 2}).limit(1)
{ "_id" : ObjectId("******001"), "hoge_id" : 1, "satousan" : 2 }
> db.sorich.find({ "satousan" : 2}).limit(1).count()
3

limitで1件に絞ってるのに、countの結果が3件。
つまりlimitしても条件に合致した件数を返すようになっている。
対処はシンプルで

console
> db.sorich.find({ "satousan" : 2}).limit(1).count(true)
1

引数に真偽値:trueをおけばOK

6
6
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
6
6