Search code examples
mongodbmongodb-queryphp-mongodb

How to get conditional fields in Mongodb


Hello good developers,

I am new to MongoDB and trying to fetch conditional data for my requirements.

I have the following collection:

 [
{
    "id":10001,
    "name":"Test 1",
    "status":"live",
    "traffics":[
        {
            "id":"1a3s5d435a4sd",
            "status":"",
        },
        {
            "id":"1a3s5d44as54d35a4sd",
            "status":"CMP",
        },
        {
            "id":"a3s5d454asd34asd",
            "status":"",
        },
        {
            "id":"1a35sd45a4sd34asd3",
            "status":"TERM",
        },
        {
            "id":"as35d435a4sd354as3d43asd4",
            "status":"CMP",
        },
        {
            "id":"135as4d5a4sd354a3s5d43asd",
            "status":"CMP",
        },
        {
            "id":"123as1d31a3d12ads13as",
            "status":"TERM",
        }
    ]

},
{...},{...}
]

I want to get data like these

ID, Name, count traffics as Starts, count (traffics where status = "CMP") as completes, count (traffics where status = "TERM") as Terminates, count (traffics where status = "") as Abandons

I am trying to run following command

db.inventory.aggregate( { $project: {id: 1, status: 1, starts: {$size: "$traffics"}, _id: 0}})

but I don't know how to get conditional data in there


Solution

  • I was able to modify @Yones answer a little bit so that I can get counts of the records based on conditions.

    so here's my query for this.

    db.collection.aggregate({
      $project: {
        id: 1,
        name: 1,
        status: 1,
        starts: {$size: "$traffics"},
        completes: {
            $size: {
                $filter: {
                input: "$traffics",
                as: "item",
                cond: {
                    $eq: [
                        "$$item.status",
                        "CMP"
                        ]
                    }
                }
            }
        },
        terminates: {
            $size: {
                $filter: {
                input: "$traffics",
                as: "item",
                cond: {
                    $eq: [
                        "$$item.status",
                        "TERM"
                        ]
                    }
                }
            }
        },
        abandons: {
            $size: {
                $filter: {
                input: "$traffics",
                as: "item",
                cond: {
                    $eq: [
                        "$$item.status",
                        ""
                        ]
                    }
                }
            }
        },
        _id: 0
      }
    })
    

    I am simply Filtering out the records based on my conditions using $filter

    And then I am calculating its size using $size.

    Here's working example for this answer: https://mongoplayground.net/p/TcuLlJShclA