davood rokhbakhsh
davood rokhbakhsh

Reputation: 41

Mongodb use $elemMatch into $filter

I have a document like this:

I need to return the documents and filter the nested array (lessons) where any item of subLessons into input array

[{
  "_id": {
    "$oid": "6081fedbee5d133dbffb42eb"
  },
  "name": "my quiz",
  "lessons": [
    {
      "_id": "460c42e1-b0b7-437e-ab63-c59cce8ced0d",
      "name": "section",
      "subLesson": [
        {
          "$oid": "6081fed9ee5d133dbffb3cba"
        },
        {
          "$oid": "6081fed9ee5d133dbffb3cc0"
        }
      ]
    },
    {
      "_id": "f7b5c95f-1a68-42ca-880c-22ef3831ff03",
      "name": "ffff",
      "subLesson": [
        {
          "$oid": "6081fed9ee5d133dbffb3cbb"
        }
      ]
    }
  ]
}
}]

I wrote the following query but it does not work. I do not know how to use $elemMatch in $filter

db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      lessons: {
        $filter: {
          "input": "$lessons",
          "as": "lesson",
          "cond": {
            "$$lesson.subLesson": {
              "$elemMatch": {
                "$in": [
                  ObjectId("6081fed9ee5d133dbffb3cba")
                ]
              }
            }
          }
        }
      }
    }
  }
])

I am trying to find the record such that the result looks like the following.

[{
  "_id": {
    "$oid": "6081fedbee5d133dbffb42eb"
  },
  "lessons": [
    {
      "_id": "460c42e1-b0b7-437e-ab63-c59cce8ced0d",
      "name": "zzzz",
      "subLesson": [
        {
          "$oid": "6081fed9ee5d133dbffb3cba"
        },
        {
          "$oid": "6081fed9ee5d133dbffb3cc0"
        }
      ]
    }
  ]
},
}]

Can anyone please help out to understand how can I make this work thanks

Upvotes: 3

Views: 1233

Answers (1)

varman
varman

Reputation: 8894

You can use $in directly

db.collection.aggregate([
  {
    $project: {
      lessons: {
        $filter: {
          input: "$lessons",
          cond: {
            $in: [ ObjectId("6081fed9ee5d133dbffb3cba"), "$$this.subLesson" ]
          }
        }
      }
    }
  }
])

Working Mongo playground

Update 1

db.collection.aggregate([
  { "$unwind": "$lessons" },
  {
    "$match": {
      "lessons.subLesson": {
        $in: [ ObjectId("6081fed9ee5d133dbffb3cba"),  ObjectId("6081fed9ee5d133dbffb3cbb") ]
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      name: { $first: "$name" },
      lessons: { $push: "$lessons" }
    }
  }
])

Mongo Playground

Upvotes: 3

Related Questions