I am trying to count the number of documents with a matching criteria in a nested field.
My schema is defined as follows:
let userSchema = new Schema({
//...
interests: [{
type: Schema.Types.ObjectId,
ref: 'Interests'
}],
//...
});
let interestSchema = new Schema({
id: ObjectId,
name: {
type: String,
required: true
},
//...
});
The count must reflect how many times an interest with the same name is choosed by the users.
For example, I must have a result of 2 with the interest 'coding' in the following documents:
{
//Other Fields of user 1
"interests": [
{
"id": "XXX"
"name": "coding"
},
{
"id": "YYY"
"name": "surfing"
}]
}
{
//Other Fields of user 2
"interests": [
{
"id": "ZZZ"
"name": "coding"
}
]
}
I looked into the countDocuments method, but it doesn't seem to allow this kind of count.
EDIT + First solution:
This is how I managed to solve it:
const res = await UserModel.aggregate([
{
$unwind: '$interests'
},
{
$lookup: {
from: "interests",
localField: "interests",
foreignField: "_id",
as: "interests"
}
},
{
$match:{
"interests.name": name
}
},
{
$count: "count"
}
]);
return res[0].count;
The fact that the interests is a referenced type, I can not query for its name unless I pass the lookup
stage. I am not sure if this is a good solution regarding performance, since the unwind
stage must pass through all the users of the database and create a new element for each of their interests. This why I am not posting it as an answer