Home > Enterprise >  MongoDB collection find method doesn't work not in order
MongoDB collection find method doesn't work not in order

Time:08-22

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"]

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

CodePudding user response:

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
  }
})
  • Related