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 – query for array of objects containing two values

I’m creating a chat app, and when a user starts a new conversation, I want to check if a conversation between those two users already exists.

My Conversation modal looks something like:

  {
    members: {
      type: [
        {
          username: String,
          email: String,
          id: String,
          avatar: String,
        },
      ],
    },
  },

And to find all conversations where one of the members contains a user’s ID, I use

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

db.collection.find({
      members: { $elemMatch: { id: userID } },
})

Which works perfectly.

But I can’t figure out how to find Conversations where the members include user1ID and user2ID

>Solution :

you can use $all operator too check if the conversation members have all the specified user ids

db.collection.find({
  "members.id": {
    "$all": [
      user1ID,
      user2ID
    ]
  }
})

playground

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