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

conditional filter in query mongodb

I have 3 user roles stored in my users’ collection [supervisors, markets, clients].

The market wants to perform a search query to find the users,

I want the market to be able to list all the users except for the markets,

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 want him to be able to see only himself, and to exclude the other markets.


In real life,

The data looks as follows:

[
  {
    "role": "supervisor",
    "name": "S1",
    "branch": "School #A",
    "id": 1
  },
  {
    "role": "market",
    "name": "M1",
    "branch": "School #A",
    "id": 2
  },
  {
    "role": "market",
    "name": "M2",
    "branch": "School #A",
    "id": 3
  },
  {
    "role": "client",
    "name": "C1",
    "branch": "School #A",
    "id": 4
  },
  {
    "role": "client",
    "name": "C2",
    "branch": "School #A",
    "id": 5
  }
]

I want to perform a query which should return this output:

[
  {
    "role": "supervisor",
    "name": "S1",
    "branch": "School #A",
    "id": 1
  },
  {
    "role": "market",
    "name": "M1",
    "branch": "School #A",
    "id": 2
  },
  {
    "role": "client",
    "name": "C1",
    "branch": "School #A",
    "id": 4
  },
  {
    "role": "client",
    "name": "C2",
    "branch": "School #A",
    "id": 5
  }
]

The query should exclude this document:

  {
    "role": "market",
    "name": "M2",
    "branch": "School #A",
    "id": 3
  }

How to perform this query.

I am using mongosh.

# this is how the command looks like at the moment:
$ db.users.find({  })

Please note:

I can’t do it like this:

# this is how the command looks like at the moment:
$ db.users.find({ id: { $ne: 3 } })

Because more users (markets) will register everyday.

>Solution :

You can use $or for this:

db.collection.find({
  $or: [
    {role: {$ne: "market"}},
    {id: 2}
  ]
})

See how it works on the playground example

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