annyoung

mongodb combine two queries with aggregate 본문

데이터베이스

mongodb combine two queries with aggregate

nopsled 2022. 1. 25. 18:47

Use $facet when you wanna combine two queries

[
    {
        "$facet": {
            "all": [
                {
                    "$match": {
                        "project": ObjectId("61d533c23186e90323d116c3"),
                    }
                },
                {"$count": "TotalCount"},
            ],
            "completed": [
                {
                    "$match": {
                        "project": ObjectId("61d533c23186e90323d116c3"),
                        "$or": [
                            {"status": "CONSIGNMENT_SUBMIT"},
                            {"status": "AGENCY_SUBMIT"},
                        ]
                    }
                },
                {"$count": "TotalCount"},
            ],
            "noResponse": [
                {
                    "$match": {
                        "project": ObjectId("61d533c23186e90323d116c3"),
                        "status": "DEPLOY_OK",
                    }
                },
                {"$count": "TotalCount"},
            ],
            "onGoing": [
                {
                    "$match": {
                        "project": project_id,
                        "$or": [
                            {"status": "CONSIGNMENT_START"},
                            {"status": "RETAKE"},
                            {"status": "AGENCY_START"},
                        ]
                    }
                },
                {"$count": "TotalCount"},
            ],
        }
    },
    {"$unwind": "$all"},
    {"$unwind": "$completed"},
    {"$unwind": "$noResponse"},
    {"$unwind": "$onGoing"},
    {
        "$project": {
            "all": "$all.TotalCount",
            "completed": "$completed.TotalCount",
            "noResponse": "$noResponse.TotalCount",
            "onGoing": "$onGoing.TotalCount"
        }
    }
]

 

Comments