Mongoid: 埋め込み (embeds_many) ドキュメントのクエリ
概要
これらは私のクラスです:
class Ticket
include Mongoid::Document
embeds_many :transitions
end
class Transition
include Mongoid::Document
embedded_in :ticket
field :to, type: String
field :created_at, type: DateTime
end
たとえば、次のようなトランジションを持つチケットがあります。
[#<Transition _id: 663b468deebb9d417d981152, to: "created", created_at: 2024-05-08 09:31:57.855 UTC>,
#<Transition _id: 663b47cceebb9d417d981153, to: "solved", created_at: 2024-05-08 09:37:16.424 UTC>,
#<Transition _id: 663b47ceeebb9d417d981154, to: "working", created_at: 2024-05-08 09:37:18.717 UTC>,
#<Transition _id: 663b47d0eebb9d417d981155, to: "pending", created_at: 2024-05-08 09:37:20.989 UTC>]
最後のトランジションに次のプロパティがあるチケットを検索したいと考えています。
Ticket.where(:'transitions.to' => "solved", :"transitions.created_at".lte => Time.now - 24.hours)
最後の遷移のみに一致するようにクエリを変更するにはどうすればよいですか?
解決策
何度も壁にぶつかりましたが、集計パイプラインを使用して、必要な方法でドキュメントをフィルタリングすることができました。
Ticket.collection.aggregate(
[
{
"$project": {
_id: 1,
transitions: {
"$slice": [
"$transitions",
-1
]
}
}
},
{
"$match": {
"transitions.created_at": {
"$lte": Time.now.utc - 24.hours
},
"transitions.to": {
"$in": states
}
}
},
{
"$project": {
_id: 1
}
}
]
).to_a
3つのステージを追加しました。
https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://mongoplayground.net/p/UprsfaP0clE