我有一个公会
集合。在 Guilds
中,我有数组属性:
"latestActivity" : [
{
"username" : "Zlotte",
"img" : "necromancer.png",
"borrowGold" : true,
"amount" : "3",
"createdAt" : "2019-08-23"
},
{
"username" : "Zlotte",
"img" : "necromancer.png",
"borrowGold" : true,
"amount" : "3",
"createdAt" : "2019-08-23"
},
]
现在我需要通过用户名
和borrowGold
来统计所有这些最新事件。我怎么做 ?这是我当前的功能:
const borrowedToday = await Guild.find({
"members.username": user.username,
"latestActivity.username": user.username,
"latestActivity.borrowGold": true,
"latestActivity.createdAt": todayDate
}).count();
console.log(borrowedToday);
但这会返回我1
,可能是因为它计数的是找到的guild
本身,而不是latestActivities
。
最佳答案
您可能必须将其汇总才能获得高效且可靠的结果。
您应该包括一个消除 $match
阶段,然后是一个 $project
阶段,以获取与一组给定过滤条件匹配的子文档的大小。例如:
const result = await Guild.aggregate([
{ $match: {
"members.username": user.username,
"latestActivity.username": user.username,
"latestActivity.borrowGold": true,
"latestActivity.createdAt": todayDate
}},
{
$project: {
"timesBorrowed": {
"$size": {
"$filter": {
"input": "$latestActivity",
"as": "items",
"cond": {
"$and": [
{ "$eq": [ "$$items.borrowGold", true ] },
{ "$eq": [ "$$items.createdAt", todayDate ] }
]
}
}
}
}
}
}]);
if (result) {
const timesBorrowed = result[0].timesBorrowed;
console.log(timesBorrowed);
} else console.error('Error.')
编辑
我使用提供的数据在本地进行了测试,并且成功获取了特定用户当天借入黄金的次数。您可以轻松修改聚合管道以提取借入的总金额。
关于node.js - Mongoose 按用户名和类型对数组中的元素进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57626552/