Mongoid-替换在belongs_to关系中的查找/联接中数组的第一个元素

时间:2019-01-18 11:56:44

标签: ruby mongodb mongoid

让我们假设这个简单的关系:

class Thing
  belongs_to :user # Not embedded!
end

Thing上的简化聚合中,我们要获取用户对象:

{ :$match => { ... } },
# Get user from belongs_to relation
{ :$lookup => {
        from: 'users',
        localField: 'user_id',
        foreignField: '_id',
        # Always has one element, because it's a belongs_to relation
        as: 'user'
      } },

在聚合中,有两种方法可以将字段替换为数组的第一个元素。

  1. 使用addFieldsarrayElemAt
  { :$addFields => { user: { :$arrayElemAt => ['$user', 0] } } }
  1. 使用unwind(假设数组中有一个元素):
  { :$unwind => { path: '$user' } }

问题:我更喜欢unwind,因为它看起来更干净,但是看到人们经常使用第一种方法。是更快还是“更好的实践”?

0 个答案:

没有答案