2016-12-05 63 views
1

我是下面的模式。檢查子文件的子文件中是否存在值

var UserSchema = new Schema({ 
    messages: [{ 
     username: String, 
     read: [{ 
      type: { type: String, enum: ['A','B','C'] }, 
     }] 
    }], 
}); 

var MySchema = new Schema({ 
    users: [UserSchema] 
}); 

我需要算多少次在MYSCHEMA每個用戶的最後一條消息沒有讀值「A」

我需要使用聚合,這樣我可以加入一個現有的查詢。

回答

1

這應該工作,如果它不請包括一些示例數據和預期的結果,讓我稍後會更新我的答案是:

db.collection.aggregate([ 
    { 
    $unwind: '$users', 
    }, 
    { 
    $project: { 
     lastMessage: { 
     $arrayElemAt: ['$users.messages', -1], 
     }, 
    }, 
    }, 
    { 
    $unwind: '$lastMessage.read', 
    }, 
    { 
    $group: { 
     _id: '$_id', 
     read: { 
     $push: '$lastMessage.read', 
     }, 
    }, 
    }, 
    { 
    $match: { 
     read: { 
     $nin: ['A'] 
     } 
    } 
    }, 
    { 
    $count: 'count' 
    } 
])