kiran Gopal kiran Gopal - 2 months ago 6
Node.js Question

how to retrieve a document with some parameters excluded in the nested array in mongo?

I have the attached document structure. I need to retrieve the document with only some parameter.

For example
I need the data to be like this.

{
"_id": "57f36d71fb1ef61bd84f866b",
"testMaxScore": 235,
"testMaxTime": 60,
"inviteId": "57f0a97d11594560c02a8f43",
"testName": "Sr. Interactive Developer l1",
"sectionList": [
{
"sectionName": "Java MCQ",
"sectionInfo": "Some info",
"questionList": [
{
"_id": "57ea3d003f2ec2cbbe98bbb9",
"question": ""
},
{
"_id": "57ea3d003f2ec2cbbe98bbb9",
"question": ""
}
]
}
]


enter image description here

How can i acheve this ?
I am using mongoose

Can anyone help me on this

Thanks,
Kiran

Answer

Possible through the aggregation framework. Consider running an aggregation operation that has a single pipeline with the $project operator to project just the fields you want.

In the above example, you would run it as

Model.aggregate([
    {
        "$project": {
            "testMaxScore": 1,
            "testMaxTime": 1,
            "inviteId": 1,
            "testName": 1
            "sectionList.sectionName" : 1,
            "sectionList.sectionInfo" : 1,
            "sectionList.questionList._id": 1,
            "sectionList.questionList.question": 1
        }
    }
]).exec(function(err, result){
    console.log(result);
})

or using the find() method:

Model.find(
    { },
    {
        "testMaxScore": 1,
        "testMaxTime": 1,
        "inviteId": 1,
        "testName": 1
        "sectionList.sectionName" : 1,
        "sectionList.sectionInfo" : 1,
        "sectionList.questionList._id": 1,
        "sectionList.questionList.question": 1
    }
).exec(function(err, result){
    console.log(result);
})