user1920
user1920

Reputation: 89

Project the size of a set type array in mongodb

I am not able to display the size of an array in projection and groupby. please find my below query.

[  
{  
    "$unwind":"$a"
},
{  
    $group:{  
        _id:"$a.acid",
        "sessions":{  
            $sum:1
        },
        "users":{  
            $addToSet:"$cid"
        }
    }
},
{  
    $project:{  
        "sessions":1,
        "users":1
    }
}

]

By the above query I can display all the users, But I want to display the size of the users set(array) only. Could anyone help me on this

Upvotes: 0

Views: 1218

Answers (1)

Vishwas
Vishwas

Reputation: 7067

You can use $size in mongo like following query:

db.collection.aggregate[{
    "$unwind": "$a"
    }, {
    $group: {
        _id: "$a.acid",
        "sessions": {
            $sum: 1
        },
        "users": {
            $addToSet: "$cid"
        }
    }
    }, {
    $project: {
        "sessions": 1,
        "users": 1,
        "size": {
            $size: "$users"
        }
    }
    }
])

EDIT AFTER OP's comment that it gives invalid operator error-

You can do something like again unwind users array and count number of users. But this involves again unwinding array so not recommended, The query will be something like following (Not tested):

db.collection.aggregate([{
    "$unwind": "$a"
}, {
    $group: {
    _id: "$a.acid",
    "sessions": {
        $sum: 1
    },
    "users": {
        $addToSet: "$cid"
    }
    }
}, {
    $unwind: "$users"
}, {
    $group: {
    _id: "$_id",
    "count": {
        $sum: 1
    },
    "sessions": {$push:"$sessions"},// u can use "sessions":{$first:"$sessions"} also.
    "users": {
        $push: "$users"
    }
    }
}])

Upvotes: 1

Related Questions