Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count distinct object located multiple in multiple arrays

Hi i have the following model:

{
    "_id" : ObjectId("5d65a9c2f62b0d437bedc87b"),
    "name" : "dsadasdsadsadsa",
    "companyBases" : [
        {
            "vehicles" : [ 
                {
                    "_id": "unique1"
                },
                {
                    "_id":"unique1"
                },
                {
                    "_id":"unique2"
                }
            ],
            "_id" : ObjectId("5d65aef598b4734a8d3994b1"),
            "name" : "Tech Parking 22",
            "__v" : 0
        },
        {
            "vehicles" : [ 
                {
                    "_id": "unique1"
                },
                {
                    "_id":"unique2"
                }
            ],
            "_id" : ObjectId("5d65aef598b4734a8d3994b3"),
            "name" : "Tech Parking 23",
            "__v" : 0
        }
    ],
    "__v" : 0
}

I would like to count distinct objects ("_id" in "vehicles" is distinct value) in "vehicles" array in "companyBases" array.

In above example pattern on counting should be:

"unique1" - 3, "unique2" - 2

So it gives 2 unique objects in "vehicles" array for whole array "companyBases".

So the output should be:

{
    "count": 2
}
like image 485
Kurs Google Avatar asked Dec 14 '25 18:12

Kurs Google


2 Answers

The following query can do the trick:

db.collection.distinct("companyBases.vehicles._id").length
like image 170
Himanshu Sharma Avatar answered Dec 18 '25 13:12

Himanshu Sharma


You can use $reduce to scan outer array and $setUnion to get an array of unique values from two other input arrays. Then you just need $size to get the length of that array:

db.collection.aggregate([
    {
        $project: {
            unique: {
                $reduce: {
                    input: "$companyBases",
                    initialValue: [],
                    in: {
                        $setUnion: [
                            "$$value",
                            "$$this.vehicles._id"
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            count: { $size: "$unique" }
        }
    }
])

Mongo Playground

like image 30
mickl Avatar answered Dec 18 '25 13:12

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!