I want to $match where a field of an array of objects is not equal to the _id

[
  {
    "_id": ObjectId("648031bd784fbf6081de41cf"),
    "orgId": 1,
    "applications": {
      "_id": ObjectId("6479ddda073ced427d04e9dd"),
      "orgId": 1,
      "firstTimeInstalled": [
        {
          "refId": ObjectId("648031bd784fbf6081de41cf"),
          "installDate": "2023-06-08T09:18:49.233+00:00"
        },
        {
          "refId": ObjectId("6479ddda073ced427d04e9dd"),
          "installDate": "2023-06-08T09:18:49.233+00:00"
        }
      ]
    }
  },
  {
    "_id": ObjectId("648031bd784fbf6081de41cd"),
    "orgId": 1,
    "applications": {
      "_id": ObjectId("6479ddda073ced427d04e9dd"),
      "orgId": 1,
      "firstTimeInstalled": [
        {
          "refId": ObjectId("648031bd784fbf6081de41cf"),
          "installDate": "2023-06-08T09:18:49.233+00:00"
        },
        {
          "refId": ObjectId("6479ddda073ced427d04e9dd"),
          "installDate": "2023-06-08T09:18:49.233+00:00"
        }
      ]
    }
  }
]

i have a dataset like this. I want to filter out the docs where any of the applications.firstTimeInstalled.refId is not equal to the _id. So in this I should get back the second doc only because in the first document, the _id is same as the first refId in firstTimeInstalled

I tried

db.collection.aggregate([
  {
    $match: {
      "applications.firstTimeInstalled.refId": {
        $ne: "$_id"
      }
    }
  }
])

but still it is giving back both the docs.

here is a demo playground

Hello @schach_schach,

The $match can’t allow checking the internal fields condition directly, you need to use $expr operator, $not and $in operator to match your condition,

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $not: {
          $in: ["$_id", "$applications.firstTimeInstalled.refId"]
        }
      }
    }
  }
])

Playground

3 Likes

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