简体   繁体   中英

MongoDB - find documents with couple conditions

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!

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"
          }
        }
      }
    }
  ]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM