Negative and positive elematch in the same query

Hi let say that I have the following scheme:

      [{
        "labels": [
          {
            "id": "5ede180af845340001ecafd0",
            "category": "lighting_condition",
            "value": "Day",
            "source": "MDB 1.0"
          },
          {
            "id": "5ede180af845340001ecafd1",
            "category": "avg_ego_speed",
            "value": 24,
            "source": "MDB 1.0"
          },
          {
            "id": "5ede180af845340001ecafd3",
            "category": "ped_objects",
            "value": 12,
            "source": "MDB 1.0"
        ]
      },
      {
        "labels": [
          {
            "id": "5ede180af845340001ecafdb",
            "category": "lighting_condition",
            "value": "Day",
            "source": "MDB 1.0"
          },
          {
            "id": "5ede180af845340001ecafdd",
            "category": "avg_ego_speed",
            "value": 19,
            "source": "MDB 1.0"
          },
          {
            "id": "5ede180af845340001ecafdf",
            "category": "vehicle_objects",
            "value": 19,
            "source": "MDB 1.0"
          },
          {
            "id": "5ede180af845340001ecafe1",
            "category": "ped_objects",
            "value": 8,
            "source": "MDB 1.0"
          }
        ]
      }]

And I want to get all of the documents that meet the following:

{"category": "lighting_condition","valu": "Day"}
AND not contain the label:
{"category": "vehicle_objects"}

I should get the first doc…

I tried to use the following query but without success:

{"labels":{"$all":[{"$elemMatch":{"category":"lighting_condition","value":{"$eq":"Day"}}},{"$not":{"$elemMatch":{"category": "vehicle_objects"}}}]}}

But without success, any idea?

Hello @Mordechai_Ben_Zechar,

I am not sure why you are trying to use the $all operator at all (it is used for matching all array elements). You should be just using the $elemMatch conditions for the query filter (and this works):

{
  labels: { $elemMatch: { category: "lighting_condition", value: "Day" } },
  labels: { $not: { $elemMatch: { category: "vehicle_objects" } } }
}

Hi @Prasad_Saya and thank you for your answer.

I used .net core driver and I can’t use the field name twice in the same hierarchy of the JSON.
I’m getting:
“ClassName”: “System.InvalidOperationException”,
“Message”: “Duplicate element name ‘labels’.”,

This is the reason that I used $all for several $elematch expression on the same field level

Then, use the $and operator:

{
  $and: [
      { labels: { $elemMatch: { category: "lighting_condition", value: "Day" } } },
      { labels: { $not: { $elemMatch: { category: "vehicle_objects" } } } }
] }
1 Like

Thank you , the $and operator works like charming!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.