'Mongodb search for a list of objects

I have a mongodb collection that stores student test scores with student ids, their test ids and corresponding test scores. One student can take multiple tests, i.e. the same student id might be associated with multiple test ids but a student cannot take a test twice, so the combination of student id and test id will return a unique document.

[{
  "_id": {
    "$oid": ...
  },
  "StudentId": "12345",
  "TestId": "001",
  "Score": 2
},{
  "_id": {
    "$oid": ...
  },
  "StudentId": "45125",
  "TestId": "002",
  "Score": 4
},{
  "_id": {
    "$oid": ...
  },
  "StudentId": "12345",
  "TestId": "002",
  "Score": 5
},{
  "_id": {
    "$oid": ...
  },
  "StudentId": "45125",
  "TestId": "001",
  "Score": 2
}]

I want to build a query with a list of student id and test id combinations and get the corresponding test scores.

This is the query I'd like to build to get student scores for test id 001:

TestScores.find([ { "StudentId" : "12345", "TestId": "001"}, { "StudentId": "45125", "TestId": "001"} ])

For the output:

[{
  "_id": {
    "$oid": ...
  },
  "StudentId": "12345",
  "TestId": "001",
  "Score": 2
}
,{
  "_id": {
    "$oid": ...
  },
  "StudentId": "45125",
  "TestId": "001",
  "Score": 2
}]

Is there a way in mongodb that I can accomplish this?



Solution 1:[1]

from what i understand you are looking for an $or query

try something like

TestScores.find({
  $or: [
    {
      "StudentId": "12345",
      "TestId": "001"
    },
    {
      "StudentId": "45125",
      "TestId": "001"
    }
  ]
})

demo

In your specific example since you only need to get student scores for "TestId": "001" can even go for this

TestScores.find({
  "TestId": "001"
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1