Home > Mobile >  Mongodb project inside array of object with array of object
Mongodb project inside array of object with array of object

Time:05-21

MongoDB

I have data like:-

[
  {
    review: [
      {
        title: "Title1",
        professor: [
          {
            id: "1",
            accept: false
          },
          {
            id: "2",
            accept: false
          }
        ]
      }
    ]
  },
  {
    review: [
      {
        title: "Title2",
        professor: [
          {
            id: "3",
            accept: false
          },
          {
            id: "2",
            accept: false
          }
        ]
      }
    ]
  }
]

I want title and professor array with filter of specific id (like "1") My code:- for match i use below code and it works perfectly fine

$match

{
      review: {
        $elemMatch: {
          professor: {
            $elemMatch: {
              id: "1"
            }
          }
        }
      }
}

for project i use below code

$project

{
      review: {
        title:1,
        professor:{
          $filter:{
            input: "$review.professor",        (I try only professor but give null)
            as: "professor",
            cond: {$eq:["$$professor.id",  "1" ]}
          }
        }
      }
    }

Problem is that professor show array but comes with empty data

CodePudding user response:

Playground

Unwind stage could help you.

db.collection.aggregate([
  {
    "$match": {
      review: {
        $elemMatch: {
          professor: {
            $elemMatch: {
              id: "1"
            }
          }
        }
      }
    }
  },
  {
    "$unwind": "$review"
  },
  {
    $project: {
      review: {
        title: 1,
        professor: {
          $filter: {
            input: "$review.professor",
            as: "professor",
            cond: {
              $eq: [
                "$$professor.id",
                "1"
              ]
            }
          }
        }
      }
    }
  }
])
  • Related