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

MongoDB collection find method doesn't work not in order

I am trying to get some db collection depends on users ID.

const chat = await Chat.findOne({ users });

now this will work : "users": ["630200a45d22133dbe5bec44", "630200975d22133dbe5bec41"]

but this will not work: "users": [630200975d22133dbe5bec41", "630200a45d22133dbe5bec44"]

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

Same id’s, just not in the right order.
enter image description here

>Solution :

You are looking for an exact match, so order matters. It seems what you want to be doing is to use $all, this checks all that the elements present in the input array exists in the db.

Additional you’ll want to add a size check if you want to limit it so an exact match, otherwise documents like {"users": ["630200a45d22133dbe5bec44", "630200975d22133dbe5bec41", "otherid"] } will be matched.

Overall like so:

const chat = await Chat.findOne({
  users: {
    $all: [
      "630200975d22133dbe5bec41",
      "630200a45d22133dbe5bec44"
    ]
  },
  "users.2": {
    $exists: false
  }
})

Mongo Playground

Or dynamically based on input size:

const input = [
      "630200975d22133dbe5bec41",
      "630200a45d22133dbe5bec44"
    ];

const sizeKey = `users.${input.length}`

const chat = await Chat.findOne({
  users: {
    $all: input
  },
  [sizeKey]: {
    $exists: false
  }
})
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