ตรวจสอบว่าไม่มีค่าอยู่ในเอกสารย่อยของเอกสารย่อย

ฉันสคีมาต่อไปนี้

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

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

ฉันต้องนับจำนวนเหตุการณ์ใน MySchema ที่ข้อความสุดท้ายของผู้ใช้แต่ละคนไม่มีค่าการอ่านเป็น 'A'

ฉันจำเป็นต้องใช้การรวมเพื่อที่ฉันจะสามารถเข้าร่วมกับแบบสอบถามที่มีอยู่ได้


person Guilherme Reda    schedule 05.12.2016    source แหล่งที่มา


คำตอบ (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'
  }
])
person kkkkkkk    schedule 05.12.2016