LoginSignup
0
2

More than 5 years have passed since last update.

まだfind & mapで消耗してるの?

Posted at

※基本的にmongooseユーザー向け記事です

データベースからユーザーのメールアドレスの配列を取り出したい・・・なんてことありますよね?
そういう時次のように書いていませんでしょうか。

const users = await User.find().select('email')
const emails = users.map(u => u.email)

ユーザーの件数が多かったり持っている項目が多かったりすると結構時間かかるんですよねこれ。
そこでdistinctがおすすめです。

Model.find([condition]).distinct(name)

distinctを使うとダブりのない配列が返ってきます。

const userEmails = await User.find({city: 'tokyo'}).distinct('email')
// > ['aaa@example.com', 'bbb@example.com',...]
const userEmails = await User.distinct('email', {city: 'tokyo'}) // こうも書けます
// 条件が第二引数に来るのが find や update などと異なるので私はあまり好きではありません。

これがめちゃくちゃ早いです。数秒〜数十秒vs一瞬〜数秒といったレベルで違います。

mongo shellで直接クエリを投げるとどちらも一瞬なのでデータベース自体の処理が早くなるわけではないようです。
JSに返ってくるオブジェクトサイズが大きく異なるために速度が違うと考えられます。
selectをしないとfindは速度がさらに大幅に落ちるので多分合ってると思います。)

mongodbで書くと多分こんな感じです。

const userEmails = await db.collection('users').distinct('email')

こちらも早いのかは確かめていませんが、上記の理由が合っていれば同様に高速だと考えられます。

0
2
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
2