我如何更改此archive-view-aggregation以聚合from.view.archive:true?
..同时防止重复消息的聚合..如果To用户(sessionUser)存在于To数组中,则只获取此消息之一..
if (archive === true) {
console.log('archive === ' + true);
Models.Message.aggregate([
// Match documents
{ "$match": {
"to": {
"$elemMatch": {
"username": req.session.username,
"view.archive": true,
"view.bin": false
}
},
"$or": messagingquery
}},
// Unwind to de-normalize
{ "$unwind": "$to" },
// Match the array elements
{ "$match": {
"to.username": req.session.username,
"to.view.archive": true,
"to.view.bin": false
}},
// Group back to the original document
{ "$group": {
"_id": "$_id",
"from": { "$first": "$from" },
"to": { "$push": "$to" },
"message": { "$first": "$message" },
"timesent": { "$first": "$timesent" },
"replies": { "$first": "$replies" },
"messaging": { "$first": "$messaging" }
}},
// Sort by updated, most recent first (descending)
{"$sort": {"updated": -1}}
], function (err, messages) {
if (err) {
console.log(err);
res.send(err);
}
res.json({
messages : messages,
sessionUser: sessionUser
});
});
}
UserMessageSchema对于From&到MesageSchema的数组:
var UserMessageSchema = new Schema({
user : { "type": Schema.ObjectId, "ref": "User" },
username : String,
view : {
inbox : Boolean,
outbox : Boolean,
archive : Boolean,
bin : Boolean
},
read : {
marked : { "type": Boolean, default: false },
datetime : Date
},
updated : Date
});
答案 0 :(得分:2)
我觉得我一定是对这种情况有所误解,但听起来你应该能够在第一个比赛阶段添加一个简单的$or
:
{ "$match": {
"$or" : [
{
"to": {
"$elemMatch": {
"username": req.session.username,
"view.archive": true,
"view.bin": false
}
}
},
{
"from" : {
"$elemMatch" : {
"username" : req.session.username,
"view.archive": true,
}
}
}
],
"$or": messagingquery
}}
复制不能来自$match
阶段,因为$match
会根据条件过滤文档。重复来自何处以及如何重复"重复"定义