2016-11-21 77 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