Return the last “true” value for each group

后端 未结 2 651
醉梦人生
醉梦人生 2020-12-03 23:04

I have collection in which documents are like:

{
    _id: ObjectId(),
     user: ObjectId(),  
     studentName: Str         


        
2条回答
  •  失恋的感觉
    2020-12-03 23:38

    This is a good example of need to group data by specific filed (createdAt) and then compare result set match criteria.

    1. find max by student id,
    2. match only entries by max entry = createdAt
    3. check if they are passing criteria
    4. reshape document

    Code:

    db.student.aggregate([{
       $group : {
           _id : "$user",
            created : {
                $max : "$createdAt"
            },
            documents : {
                $push : "$$ROOT"
            }
        }
     }, {
    $project : {
        _id : 0,
        documents : {
            $filter : {
            input : "$documents",
            as : "item",
                cond : {
                    $eq : ["$$item.createdAt", "$created"]
                }
            }
        }}
    }, {
    $match : {
        "documents.isAbandoned" : true
    }},
    { $unwind : "$documents" },
    {
    $project : {
        _id : "$documents._id",
        user : "$documents.user",
        studentName : "$documents.studentName",
        createdAt : "$documents.createdAt",
        isAbandoned : "$documents.isAbandoned",
     }}
    ])
    

提交回复
热议问题