Requirement: COUNT all documents in the collection WHERE objects.objectType equal to 'group' AND (objects.objectType NOT equal to 'person' && relation equal to 'Exposed_to')
Expected: will return count of all documents WHERE objects.objectType equal to 'group' AND which does not contain any (objectType:person && realtion:Exposed_to) under 'objects' array.
An example of matched document:
"objects": [
{
"objectType": "organization",
"relation": "Exposed_to"
},
{
"objectType": "group",
"relation": "Exposed_to"
}
]
An example of document that shouldn't be counted:
"objects": [
{
"objectType": "person",
"relation": "Exposed_to"
},
{
"objectType": "group",
"relation": "Exposed_to"
}
]
i have tried the following query:
.count({
'objects.objectType': 'group',
'objects': {
$elemMatch: {
$and: [{'objectType' : {$ne: 'person'}, 'relation': 'Exposed_to'}]
}
}})
but it seems to be not working correctly. i am not sure if i should use aggregation in this case- i also have less knowledge in this area.
i will be glad to get some help. thanks!
CodePudding user response:
Is it working for you? https://mongoplayground.net/p/Q-dj7_O_AJR
This playground doesn't support count
, so I replace by find
db.collection.find({
$and: [
{
"objects.objectType": "group"
},
{
objects: {
$not: {
"$elemMatch": {
"objectType": "person",
"relation": "Exposed_to"
}
}
}
}
]
})