Marcelo
Marcelo

Reputation: 585

MongoDB aggregate match by array

is there some way to match by an array, using aggregation on mongodb? I have the following structure:

students

{
  _id: 67264264726476,
  name: "Student 1",
  email: "[email protected]"
}

followups

{
  _id: 65536854685,
  student: 67264264726476,
  message: "This is a student follow up"
}

I've made the following query:

const followups = await this.modelFollowup.aggregate([
  {
    $lookup: {
      from: 'students',
      localField: 'student',
      foreignField: '_id',
      as: 'student',
    },
  },
  { $unwind: { path: '$student' } },
  {
    $match: {
      $or: [
        { 'student.name': { $regex: term, $options: 'i' } },
        { 'student.email': { $regex: term, $options: 'i' } },
      ],
    },
  },
]);

How can I make it possible to match using an array, instead of the term variable?

Upvotes: 0

Views: 2386

Answers (1)

HandsomeCoder
HandsomeCoder

Reputation: 756

If you want to match the complete list of student names and email you can check this query

Query

db.followups.aggregate([
  {
    $lookup: {
      from: "students",
      localField: "student",
      foreignField: "_id",
      as: "student",
      
    },
    
  },
  {
    $unwind: {
      path: "$student"
    }
  },
  {
    $match: {
      $or: [
        {
          "student.name": {
            "$in": [
              "abc",
              "def"
            ]
          }
        },
        {
          "student.email": {
            "$in": [
              "[email protected]"
            ]
          }
        },
      ],
    },
  },
])

Here is the link to the playground to check the query

Upvotes: 2

Related Questions