Currently, I have these MongoDB documents:
{
"_id" : ObjectId("someId1"),
"employeeId": 1,
"vehicleName": "accord"
},
{
"_id" : ObjectId("someId12"),
"employeeId": 1,
"vehicleName": "camry"
},
{
"_id" : ObjectId("someId3"),
"employeeId": 2,
"vehicleName": "civic"
},
{
"_id" : ObjectId("someId4"),
"employeeId": 2,
"motorcycleName": "shadow"
},
{
"_id" : ObjectId("someId5"),
"employeeId": 3,
"vehicleName": "corolla"
},
{
"_id" : ObjectId("someId6"),
"employeeId": 3,
"vehicleName": "elantra"
},
{
"_id" : ObjectId("someId7"),
"employeeId": 4,
"vehicleName": "sonata"
}
I am trying to create a query to return the employeeIds
that have more than record containing a vehicleName
, which in this case is only 1 and 3. I’m not sure if this can be achieved with a simple query however. Does it require an aggregate?
2
Answers
Perform a simple
$group
to get allvehicleName
. Depends on your situation, you may use either$push
or$addToSet
. Perform a$match
on the$size
of the resulting array.Mongo Playground
Since you have a
vehicleName
and amotorcycleName
field it may be worth matching documents that only have avehicleName
field first to reduce the set then use$group
to group them byemployeeId
and count how many occourances of eachemployeeId
there were. At the end you can then$match
where the count was greater than 1 like so:See HERE for a working example.