Reputation: 115
I the following schema.
var UserSchema = new Schema({
messages: [{
username: String,
read: [{
type: { type: String, enum: ['A','B','C'] },
}]
}],
});
var MySchema = new Schema({
users: [UserSchema]
});
I need to count how many occurrences in MySchema that the last message of each user don't have the read value as 'A'
I need to use aggregate, so that I can join with an existing query.
Upvotes: 1
Views: 467
Reputation: 7748
This should work, if it does not please include some sample data and expected result so that I will update my answer later:
db.collection.aggregate([
{
$unwind: '$users',
},
{
$project: {
lastMessage: {
$arrayElemAt: ['$users.messages', -1],
},
},
},
{
$unwind: '$lastMessage.read',
},
{
$group: {
_id: '$_id',
read: {
$push: '$lastMessage.read',
},
},
},
{
$match: {
read: {
$nin: ['A']
}
}
},
{
$count: 'count'
}
])
Upvotes: 1