Mongoid基于关联嵌套嵌入文档按Token ID查询Log的问题
问题根因
明确各集合的实际存储逻辑后,就能定位之前查询失效的核心原因:
Log是独立集合,通过外键字段user_id关联User,不会冗余存储关联User的内嵌tokens结构,Log自身的文档里根本不存在user.tokens._id这个路径的字段,自然无法返回匹配结果。- Mongoid的普通where查询不会自动跨集合拉取关联文档做条件匹配,这类跨集合的字段查询不能直接套用单集合的内嵌字段查询语法。
可行实现方案
方案1:两步关联查询(推荐,性能最优)
这是日常开发最常用的实现,逻辑清晰、查询效率高:
- 根据Token ID定位所属的User集合:Token是内嵌在User文档中的,User集合本身支持直接匹配内嵌的Token ID
target_user_ids = User.where('tokens._id' => BSON::ObjectId('123ABC')).pluck(:_id) - 根据拿到的User ID集合匹配对应的Log文档
matched_logs = Log.where(user_id: target_user_ids)
方案2:链式关联查询(代码更简洁)
可以先给User模型补充Log的反向关联,简化查询逻辑:
class User include Mongoid::Document embeds_many :tokens # 新增Log的反向关联 has_many :logs, inverse_of: :user end
补充关联后,直接通过Token定位User,再顺着关联取Log即可:
target_token_id = BSON::ObjectId('123ABC') matched_logs = User.where('tokens._id' => target_token_id).flat_map(&:logs)
方案3:聚合查询实现(适合多表联算的特殊场景)
如果需要单查询完成匹配,可以用聚合管道手动关联两个集合,手动匹配Token条件:
Log.collection.aggregate([ { '$lookup': { from: 'users', localField: 'user_id', foreignField: '_id', as: 'user_info' } }, { '$unwind': '$user_info' }, { '$match': { 'user_info.tokens._id': BSON::ObjectId('123ABC') } } ])
注意:这种全量关联扫描的方式在数据量大时性能较差,非必要不使用
内容的提问来源于stack exchange,提问作者victorhazbun
相关产品推荐
相关产品推荐

