在 Mongoid 中按 id 查找嵌入式文档

Find embedded document by id in Mongoid

如何在 mongoid 中通过 _id 查找嵌入的文档? 我有 Childrens 嵌入 Parent,我想通过它的 id 找到一个:

Parent.where('children._id' => BSON::ObjectId(children_id).first

但这返回的 Parent 包含给定 ID 的 Children,而不是 Children 本身。

谢谢

如果您已经有了父项 - 只需遍历并在子数组中搜索子项

children = parent.children.select {|child| child._id == children_id }