【发布时间】:2017-06-28 16:59:12
【问题描述】:
我有两种模式,一种是User,另一种是Pet。 Pet 架构包含我想在 User.aggregate 管道内 $sum 的信息。
Mongo 版本是 3.4.1。
用户架构:
pets: [{type: Schema.Types.ObjectId, ref: 'Pets'}]
宠物架构:
owner: {type: Schema.Types.ObjectId, ref: 'User'},
petLost: {
lost : {type: Boolean, default: false},
lostDate : {type: String},
selectedComRange: {type: Number, default: 5},
circumstances : {type: String},
extraInfoLost : {type: String},
rewardCheck : {type: Boolean, default: false},
reward : {type: String},
addressLost : {type: String},
}
这是查找:
{'$unwind': '$pets'},
{
'$lookup': {
'from' : 'pets',
'localField' : '_id',
'foreignField': '_id',
'as' : 'lostPets'
}
},
{'$unwind': {path: '$lostPets', preserveNullAndEmptyArrays:true}}
这是我想要达到的条件:
'lostPet_count': {
'$sum': {
'$cond': [{'$eq': ['$lostPets.lost', true]}, 1, 0]
}
}
聚合管道:
User.aggregate([
{
$group: {
_id : null,
'users_count' : {
'$sum': {
'$cond': [{'$eq': ['$role', 'user']}, 1, 0]
}
},
'volunteer_count': {
'$sum': {
'$cond': [{'$eq': ['$isVolunteer', true]}, 1, 0]
}
},
'pet_count' : {
'$sum': {
$size: '$pets'
}
},
'lost_pet' : {
'$sum': {
**// how can i call another collection and $sum some data?**
}
}
}
},
{
'$project': {
'_id' : 0, 'role': '$_id',
'statistics': {
'users' : '$users_count',
'volunteers': '$volunteer_count',
'pets' : '$pet_count'
}
}
}
]).exec((err, result) => {
if (err) {
console.log(err);
}
res.status(200).json(result);
});
如何将信息从 Pet 架构注入 'lost_pet' 属性?
【问题讨论】:
-
看看$lookup
-
@felix 这就是我现在正在做的事情,如果我能做到,我会发回结果
-
当我尝试使用 `{ '$unwind': '$pets'} 展开数组时,出现此错误:
MongoError: The argument to $size must be an array, but was of type: objectId--- 这是架构类型:pets : [{type: Schema.Types.ObjectId, ref: 'Pets'}],
标签: mongodb mongoose mongodb-query aggregation-framework