0

I am new in node js and I need a query for my node js script, so that it return query item from my MongoDB. What I am doing, I applying a query using node js for particular questionId which score is 1 inside MongoDB data are stored in array form, so that query will return only score's 1 questionId not score's 0.

{
"_id": "57cfc7b86f0e51ee17d4c512",
"question": [
        {
        "questionId": "57ce608e2a0d6cad8c48ef8f",
        "score": 1,
        },
        {
        "questionId": "57ce608e2a0d6cad8c48ef90",
        "score": 0,
        },
        {
        "questionId": "57ce608e2a0d6cad8c48ef91",
        "score": 0,
        }
]
}

The node js code query that i applying is I have tried two queries but they return all array items query = {'question.score':1}; query = {'question':{$eq:{'score':1}}};

function(){
             var query = {'question.score':1};
              childQuizInfo.findOne(query,function(err,data){
                        if(err) return next(err);
                        res.send(data);
                      });
                    }

I am using this query so that it return response only "questionId":"57ce608e2a0d6cad8c48ef8f", but it return all items of array.

  • 1
    As the array *question* is a field of the document, you will always get back all the content. You could not achieve this with a plain query, instead try tu use an *agregation* [documentation](https://docs.mongodb.com/manual/aggregation/) – Mario Santini Sep 08 '16 at 09:33
  • You can try the answer in [here](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection). – Tan Le Sep 08 '16 at 09:34

2 Answers2

1

Use aggregation pipeline:

childQuizInfo.aggregate([{ $unwind: "$question" }, { $match: { "question.score": 1 } }, { $project: { "_id": 0, "questionId": "$question.questionId" } } ]);

Useful link:

http://excellencenodejsblog.com/mongoose-aggregation-count-group-match-project/

https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

Dhruv
  • 173
  • 11
1

This will work for you:

db.getCollection('Test').aggregate([{$unwind:"$question"},{$match:{"question.score":1}}]);
shapiro yaacov
  • 2,308
  • 2
  • 26
  • 39
Shantanu Madane
  • 617
  • 5
  • 14