2016-11-21 74 views
0

我有查询是这样的:

{"$match": {$or: [{"to": system.mongoose.Types.ObjectId(userId)}, {"from": system.mongoose.Types.ObjectId(userId)}]}}, 
     {"$sort": {"createDate": -1}}, 
     { 
      "$group": { 
       "_id": "$conversationId", 
       "from": {"$first": "$from"}, 
       "to": {"$first": "$to"}, 
       "content": {"$first": "$content"}, 
       "createDate": {"$first": "$createDate"}, 
       "unreaded": {"$sum": 1} 
      } 

     }, 

我不需要编辑主$match我只需要得到unreaded消息的总和,

我需要的是这样的:"unreaded": {"$sum": 1, {$match: {unreaded: true}}}

任何解决方案?

回答

0

使用$cond

"unreaded": {"$sum": {$cond: {if: "$unreaded", then: 1, else: 0} }} 

文档:
https://docs.mongodb.com/manual/reference/operator/aggregation/cond/

+0

如何我还添加其他COND呢?我还需要'$ to''等于'system.mongoose.Types.ObjectId(userId)'需要这样的一些事情:''unreaded“:{”$ sum“:{$ cond:{if:”$ unreaded“ &&(“$ to”== system.mongoose.Types.ObjectId(userId)),然后:1,else:0}}}? – Vladimir