Jason McFarlane
Jason McFarlane

Reputation: 2175

Mongoose get documents where id does NOT exist inside nested object

I am trying to query a list of documents where a userid DOES NOT exist inside an array of objects.

The database (documents) looks like this:

[
  { 
    title: 'object 1',
    description: 'description 1',
    members: [
      { profile: { id: '123', ...}, data: {} },
      { profile: { id: 'abc', ...}, data: {} },
      { profile: { id: 'def', ...}, data: {} }, 
    ]
  },
  { 
    title: 'object 2',
    description: 'description 3',
    members: [
      { profile: { id: 'aaa', ...}, data: {} },
      { profile: { id: 'bbb', ...}, data: {} },
      { profile: { id: 'ccc', ...}, data: {} }, 
    ]
  },
]

Given that my userid is 'aaa' I am trying to query all documents where I am NOT a member.

I can successfully query all documents where my userid exists using this code:

await this._repository.findManyByQuery(
  {
    members: {
      $elemMatch: {
        "profile.id": "aaa",
      },
    },
  },
)

However I am looking to query all objects where my ID DOES NOT exist. I have tried using $ne however it still returns the documents where the user id exists

members: {
  $elemMatch: {
    "profile.id": { $ne: "aaa" },
  },
},

I guess I am looking for the opposite of $elemMatch but for querying inside an arry

Upvotes: 0

Views: 868

Answers (1)

J.F.
J.F.

Reputation: 15235

You can use $not to negate the $elemMatch like this:

await this._repository.findManyByQuery({
  members: {
    "$not": {
      $elemMatch: {
        "profile.id": "aaa"
      }
    }
  }
})

Example here

Upvotes: 1

Related Questions