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 = 1actionid=1的计数。请尝试通过aggregation进行操作

Comment.aggregate([{$unwind: '$actions'},
                   // filter the actionid is 1
                   {$match: {'actions.actionid': '1'}},
                   //
                   {$group: {_id: 'actions.actionid',
                             actioncount: {$sum: 1}
                             }}
   ])

09-20 17:16