Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

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

Example here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading