studentneedshelp
studentneedshelp

Reputation: 53

Mongodb Query with conjoined data points

I'm trying to create a query that can pull this information from my database using just the type score when it's less than 70 and when it's of type exam:

  {"_id":0,"name":"aimee Zank",
 "scores":[{"score":1.463179736705023,"type":"exam"},      
{"score":11.78273309957772,"type":"quiz"},{"score":35.8740349954354,"type":"homework"}]}

I'm not getting any errors and it's turning up blank. Here's the query I'm trying to use:

db.students.find({"scores":[{"score":{$lt:70},"type":"exam"}]}).pretty

Any help would be appreciated :)

Upvotes: 1

Views: 54

Answers (1)

Rahul Raj
Rahul Raj

Reputation: 3459

That is not how you match elements inside array. Use $elemMatch :

db.students.find({"scores":{$elemMatch:{score:{$lt:70},type:"exam"}}})

Update: OP marked the post as "not answered" and then come with twisted requirement. Going forward, make sure you post a seperate question for your entirely new requirements or state your problem properly, dont extend it as the time flies. However, here's the filter query using aggregation framework:

db.collection.aggregate([
  {$addFields:{scores:{$filter:{
     input:"$scores",
     as:"score",
     cond:{$and:[{$eq:["$$score.type","exam"]},{$lt:["$$score.score",70]}]} 
   }}}}
])

This filters all exams that have score less than 70.

Upvotes: 1

Related Questions