Check If field exists in an sub-document of an Array

后端 未结 4 540
后悔当初
后悔当初 2021-02-12 15:38

I have a schema that is similar to this.

{id: Number,
  line_items: [{ 
    id: String,
    quantity: Number,
    revi         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-12 16:35

    let rankers = [
                        {
                            "_id": "5e4d4a13e0eb7b0733f27a18",
                            "totalMarks": 400,
                            "correct": 78,
                            "incorrect": 22,
                            "obtainMarks": 290,
                            "attemptCount": 100,
                            "timeTaken": 0,
                            "rank": 0,
                            "userRank": 1
                        },
                        {
                            "_id": "5e4d4a13e0eb7b0733f27a18",
                            "totalMarks": 400,
                            "correct": 77,
                            "incorrect": 21,
                            "obtainMarks": 287,
                            "attemptCount": 98,
                            "rank": 0,
                            "userRank": 2
                        },
                        {
                            "_id": "5e4d4a13e0eb7b0733f27a18",
                            "totalMarks": 400,
                            "correct": 76,
                            "incorrect": 21,
                            "obtainMarks": 283,
                            "attemptCount": 97,
                            "timeTaken": 0,
                            "userRank": 3
                        }
        ]
    

    In the rankers collection rank and timeTaken key is missing in some documents so please

    Results.aggregate([
    {
        $project: {
            "totalMarks": 1,
    
            "correct": "$correct",
            "incorrect": "$incorrect",
            "obtainMarks": "$obtainMarks",
            "attemptCount": "$attemptCount",
            "timeTaken": {
                $cond: {
                    if: { "$eq": [{ "$type": "$timeTaken" }, "missing"] },
                    then: 0,
                    else: "$timeTaken"
                }
            },
            "rank": {
                $cond: {
                    if: { "$eq": [{ "$type": "$rank" }, "missing"] },
                    then: 0,
                    else: "$rank"
                }
            }
        }
    }])
    

提交回复
热议问题