【问题标题】:Mongoid query nested embed document through belongs to and embeds manyMongoid查询嵌套embed文档通过属于和嵌入多个
【发布时间】:2021-07-21 03:57:28
【问题描述】:

鉴于以下文档,我正在尝试查找给定令牌 ID 的日志文档。

class Log
  include Mongoid::Document

  belongs_to :user
end

class User
  include Mongoid::Document

  embeds_many :tokens
end

class Token
  include Mongoid::Document
end

我尝试了Log.where('user.tokens._id': BSON::ObjectId('123ABC'),但没有成功。有什么想法吗?

【问题讨论】:

  • 你能提供一些你收藏的样品吗?

标签: ruby-on-rails mongodb mongodb-query mongoid


【解决方案1】:

在这种情况下,您无法在 Mongoid Criteria 中从 log 导航到 user,因为它们是数据库中的不同集合(点表示法仅在使用嵌入时可用)。对于这种情况,您可以使用聚合管道:

Log.collection.aggregate([
  {
    '$lookup' => {
      from: User.collection.name,
      localField: 'user_id',
      foreignField: '_id',
      as: 'users'
    }
  },
  {
    '$match' => {
      'users.tokens' => {
        '$elemMatch' => {
          _id: { '$eq' => BSON::ObjectId('123ABC') }
        }
      }
    }
  }
]).map { |doc| Log.instantiate(doc) }

查找的工作方式类似于 SQL docs 中的联接。

Mongoid 中的aggregate 返回BSON::Documents 的集合,因此我们使用Log.instantiate 从它们创建Log 实例。

【讨论】:

  • 代码看起来不错,但是完成的时间太长,它返回nil
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多