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.

2
  • 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 Commented Sep 8, 2016 at 9:33
  • You can try the answer in here. Commented Sep 8, 2016 at 9:34

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

1

This will work for you:

db.getCollection('Test').aggregate([{$unwind:"$question"},{$match:{"question.score":1}}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.