B
B
bpGusar2020-03-12 12:33:16
MongoDB
bpGusar, 2020-03-12 12:33:16

How to perform a full match search on an array?

There is a model

Schema({
  members: [
    {
      type: String,
      required: true,
      ref: "User"
    }
  ],
  createdAt: {
    type: Date,
    default: Date.now(),
    required: true
  },
  lastMessage: {
    message: {
      type: String,
      required: true
    },
    from: {
      type: String,
      required: true
    },
    createdAt: {
      type: Date,
      required: true
    }
  },
  messages: [
    {
      createdAt: {
        type: Date,
        required: true
      },
      message: {
        type: String,
        required: true
      },
      from: {
        type: String,
        ref: "User",
        required: true
      }
    }
  ]
});


This is the code I use for searching
Chats.countDocuments(
      {
        members: {
          $in: ["userIdOne", "userIdTwo"]
        }
      },
      cb
    )


The problem is that the search does not follow the exact match of the $in parameter . If there are several documents where members contains at least one userId... parameter from $in , then the search will show this.

What I need is that if I set two parameters, then I need to display only those documents where there are only these two parameters, that is, by complete coincidence.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bpGusar, 2020-03-12
@bpGusar

Found a solution.
Should use $all instead of $in

Chats.countDocuments(
  {
    members: {
      $all: ["userIdOne", "userIdTwo"]
    }
  },
  cb
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question