0

I have the object below in MongoDB and my back end is using nodeJS. to retrieve the data from DB. the "_id" field is provided in the API body.

questions = [
    {
        "_id": "idq1"
        "questiontext": "some question",
        "author": "auth2",
        "Answers": []
    },
    {
        "_id": "idq2"
        "questiontext": "some question",
        "author": "auth1",
        "Answers": [
            {
                "author": "auth1",
                "comments" [...],
                "status" : "1"
            },
            {
                "author": "auth2",
                "comments" [...],
                "status" : "0"
            },
            {
                "author": "auth3",
                "comments" [...],
                "status" : "1"
            }
        ]
    }
    ]

Expected result:

I want to get an object where the status is equal to "1" my expected result is given below :

    result = {
    "_id": "idq2"
    "questiontext": "some question",
    "author": "auth1",
    "Answers": [
        {
            "author": "auth1",
            "comments" [...],
            "status" : "1"
        },
        {
            "author": "auth3",
            "comments" [...],
            "status" : "1"
        }
    ]
}

Understanding the aggregation, it always return an array, so an array should be fine too.

2
  • 1
    Does this answer your question: stackoverflow.com/questions/61533627/… Commented May 25, 2020 at 17:04
  • 1
    Thank you so much! it was a big help, I change it a bit and it works good Commented May 25, 2020 at 17:15

1 Answer 1

0

I try the solution below and it work! Thanks to @mickl for his solution on this post: MongoDB filter objects array content based on object member

const question =  await Question.aggregate([

    { $match: {_id: ObjectId(req.params.id)}}
    ,{
      $addFields: {
        Answers: {
          $filter: {
            input: "$Answers",
            cond: {
              $eq: [
                "$$this.status",
                "1"
              ]
            }
          }
        }
      }
    }
  ])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.