Search code examples
javascriptnode.jsmongodbmongoose

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

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