var commentSchema = new Schema({
text: String,
actions:[{actionid:String, actiondata:String}],
author: String
})
在获取记录时,我需要为
action = 1
计数。我想将计数作为每个评论中的额外键添加如下:{
"comments":[
{"commentData":{
"text":"temp1",
"author":"tempauthor1",
"actioncount":"2"
}},
{"commentData":{
"text":"temp1",
"author":"tempauthor2",
"actioncount":"3"
}}
]}
我需要这样的json响应。请帮忙。
最佳答案
仅过滤actionid = 1
和actionid=1
的计数。请尝试通过aggregation
进行操作
Comment.aggregate([{$unwind: '$actions'},
// filter the actionid is 1
{$match: {'actions.actionid': '1'}},
//
{$group: {_id: 'actions.actionid',
actioncount: {$sum: 1}
}}
])