nacho
nacho

Reputation: 651

mongoDB Aggregation - Match 2 conditions at the same time

I need to perform an operation that matches 2 conditions:

I have Chat model with users (array of Id's).

const ChatSchema = new Schema(
  {
    users: {
      type: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
      }]
    },
    messages: {
      type: [{
        type: Schema.Types.ObjectId,
        ref: 'Message'
      }]
    },
  },
  {
    toObject: { virtuals: true },
    toJSON: { virtuals: true },
    timestamps: true
  }
);

Aggregation Query:

return await _chat.aggregate([{
    $match: { // Here I nedd to match both cases
      $expr: { $in: [userId1, "$users"] },
      $expr: { $in: [mongoose.Types.ObjectId(userId2), "$users"] }
    }
  },
  { $addFields: { totalMessages: { "$size": "$messages" } } },
  {
    $project: {
      users: 1,
      messages: { $slice: ["$messages", -20] },
      totalMessages: 1,
      createdAt: 1
    }
  },
  {
    $lookup: {
      from: this._message.collection.name,
      localField: 'messages',
      foreignField: '_id',
      as: 'messages',
    }
  }
])

I tried using $and but it is not working in the $match stage.

Does anyone know how can I perform this?

Upvotes: 1

Views: 236

Answers (1)

turivishal
turivishal

Reputation: 36094

You can simply use $all,

{
  $match: {
    users: {
      $all: [userId1, mongoose.Types.ObjectId(userId2)]
    }
  }
}

Upvotes: 1

Related Questions