我有一个仅存储ID的集合:
grok {
match => [ "message", "PT%{NUMBER:DurationHours}H" ]
}
mutate {
add_field => { "NewDurationHrs" => "%{DurationHours}" }
}
我需要从其他藏书中获取书籍,位置和用户 我可以通过这种聚合来做到这一点:
{
"_id" : ObjectId("5b480e24d56ce43eab36c680"),
"book" : ObjectId("5b480b8a39036edbce430ab2"),
"location" : ObjectId("5b480b7a1221dbcf83b4fc89"),
"users" : [
ObjectId("5b480ae44e3ead483d051558"),
ObjectId("5b480ae44e3ead483d051557"),
ObjectId("5b480ae44e3ead483d051556")
],
}
这在mongo v4中很好用, 我知道仅在mongo v3.3.4及更高版本上支持查找引用数组的功能,我使用的版本比该版本小,我还不能升级版本。
使用此解决方案$lookup on ObjectId's in an array,我的汇总最终如下:
db.visits.aggregate([
{'$lookup': {
localField: 'book',
foreignField: '_id',
from: 'books',
as: 'book',
}
},
{'$lookup': {
localField: 'location',
foreignField: '_id',
from: 'locations',
as: 'location',
}
},
{'$lookup': {
localField: 'user',
foreignField: '_id',
from: 'users',
as: 'users',
}
},
{ '$project':
{
book: '$book',
location: '$location'
user: '$users',
}
}
])
但是结果是这样的:
db.visits.aggregate([
{'$lookup': {
localField: 'book',
foreignField: '_id',
from: 'books',
as: 'book',
}
},
{'$lookup': {
localField: 'location',
foreignField: '_id',
from: 'locations',
as: 'location',
}
},
{'$unwind': '$users' },
{'$lookup': {
localField: 'user',
foreignField: '_id',
from: 'users',
as: 'usersDetails',
}
},
{'$unwind': '$usersDetails'},
{'$group': {
_id: '$_id',
users: {'$push': '$usersDetails' }
}},
{ '$project':
{
book: '$book',
location: '$location'
user: '$users',
}
}
])
我花了一天时间试图修复它,但未成功。我需要这方面的帮助。