Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Search if Value Doesn't Exist In the sub array

Model:

const Room = new Schema({
  topic: String,
  messages: [{
    text: String,
    readByUsers: [String] // Array of users Ids, which read this message
  }]
});

Example data:

{
  topic: 'First',
  messages: [
{
      text: 'First message',
      readByUsers: ['id1', 'id3', 'id2']
    },
    {
      text: 'Second message',
      readByUsers: ['id1', 'id2'] //id3 not read this
    }
  ]
},
{
  topic: 'Second',
  messages: [
    {
      text: 'Third message',
      readByUsers: ['id1', 'id3', 'id2']
    },
    {
      text: 'Fourth message',
      readByUsers: ['id1', 'id2', 'id3']
    }
  ]
}

My goal - receive First object, because Second message was not been read by id3 user (this key not exists in readByUsers array).

Query like: Search all documents, where some of messages.readByUsers not contains specific userId

Model.find(messages.readByUsers: {$nin: [userId]})

works only if no one of messages.readByUsers not contains id, for example Model.find(messages.readByUsers: {$nin: ['id4']}) - returns both objects

like image 542
Oleg Rybnikov Avatar asked Sep 18 '25 18:09

Oleg Rybnikov


1 Answers

You can do this by using the $elemMatch operator which looks for at least one element which satisfies its conditions:

Model.find({messages: {$elemMatch: {readByUsers: {$ne: 'id3'}}}})
like image 158
JohnnyHK Avatar answered Sep 20 '25 06:09

JohnnyHK