How would I change this archive-view-aggregation to also aggregate the from.view.archive : true?
..while preventing aggregation of duplicate messages..if the From User (sessionUser) exists in the To array, then only get one of this message..
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
});
});
}
The UserMessageSchema looks like this for both the From & To arrays of the 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
});
I feel like I must be misunderstanding something about the situation, but it sounds like you should be able to add a simple $or
in the first match stage:
{ "$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
}}
Duplication can't result from a $match
stage, since $match
filters documents based on a condition. Where is the duplication coming from and how exactly is a "duplicate" defined?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.