LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】Mongoidでembeds_manyの子要素の数を条件付き取得する

Posted at

概要

以前に【Rails】Mongoidでembeds_manyの子要素の数を取得するの記事で、MongoDBにて配列要素の項目数を取得する方法を記載しました。今回は配列の項目数を取得するときに条件付きで取得する方法を書きます。

サンプル例題

前回の記事とほぼ同じですが、今回はCommentクラスに日付項目(created_at)を追加し、日付の条件で絞るような例題にします。

article.rb
class Article
  include Mongoid::Document
  field :_id, type: String
  field :title, type: String
  field :contents, type: String
  embeds_many :comments
end
comment.rb
class Comment
  include Mongoid::Document
  field :user_id, type: String
  field :post_comment, type: String
  field :created_at, type: DateTime
  embedded_in :article
end

対応方法

MongoDBでaggregateのクエリ時に使用できる$filter句を使います。これで配列要素を、条件に一致したものみで抽出できます。

sample.rb
# コレクションの取得
db = Mongoid::Clients.default
articleCollection= db[:article]
# 日付条件(30日前)
before30day = Time.now.utc - 30.days
# aggregateの実行
articleCollection.aggregate([
  {
    "$project" => {
      _id: 1,
      title: 1,
      contents: 1,
      # 30日以内のもののみでカウント
      comments_count: { "$size": { '$filter' => {
        'input' => '$comments',
        'as' => 'comments',
        'cond' => { '$gte' => ['$$comments.created_at', before30day] }
      } } }
    }
  }
]).to_a
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