让我们假设这个简单的关系:
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'
} },
在聚合中,有两种方法可以将字段替换为数组的第一个元素。
addFields
和arrayElemAt
: { :$addFields => { user: { :$arrayElemAt => ['$user', 0] } } }
unwind
(假设数组中有一个元素): { :$unwind => { path: '$user' } }
问题:我更喜欢unwind
,因为它看起来更干净,但是看到人们经常使用第一种方法。是更快还是“更好的实践”?