Wednesday 22 August 2018

get-nested-array-document-with-filter-mongo-db


Consider the Schema :

 "data": {
        "chapters": {
            "_id": "5b7c023bff64339c40613161",
            "courseworkId": "5b7c0228ff64339c40613160",
            "chapterName": "chapter1",
            "subChapters": [
                {
                    "questions": [
                        {
                     
                            "_id": "5b7c0a26ff64339c40613166",
                            "title": "test"
                        },
                        {
                            "_id": "5b7d046ee07f6e9ee72d0e38",
                            "title": "question 2"
                       
                        }
   ],
 "_id": "5b7c0446ff64339c40613162",
 "subChapterName": "subChapter9"
 }
}



GET sub document that match question ID : 5b7c0a26ff64339c40613166


1. Match the results for chapter Id
2. Go through the subchapters and see if we match the question Id and filter the results
db.chapter.aggregate([
  { "$match": {
    "_id" : ObjectId("5b7c023bff64339c40613161")
  }},         
  { "$addFields": {
    "subChapters": {
      "$filter": {
        "input": {
          "$map": {
            "input": "$subChapters",
            "as": "sc",
            "in": {
              "_id": "$$sc._id",
              "questions": {
                "$filter": {
                  "input": "$$sc.questions",
                  "as": "qu",
                  "cond": {
                      "$eq": [ "$$qu._id", ObjectId("5b7c0a26ff64339c40613166")  ]
                  }
                }
              }           
            }
          },
        },
        "as": "sc",
        "cond": {
          "$and": [
            { "$gt": [ { "$size": "$$sc.questions" }, 0 ] }
          ]
        }
      }
    }
  }}
])

No comments:

Post a Comment