0

I have the multiple nested objects and lists, like below

{
 "_id": "5a76be26ca96e22f08af2a19",
 "testId": "123",
 "testName": "summerTest",
 "subjects": [
   {
     "subjectName": "Maths",
     "testDetails": [
     {
      "testNumber": "0001",
      "startTime": "2/18/18 13:30",
      "endTime": "2/18/18 13:30",
      "testDuriation": "01:00:00",
      "questions": [
        {...}
     ]
    },
     {
      "testNumber": "0002",
      "startTime": "2/18/18 13:30",
      "endTime": "2/18/18 13:30",
      "testDuriation": "01:00:00",
      "questions": [
        {...}
     ]
    }
  ]
}

i want to select testNumber 0002 only. using mongoclient in my express js.

collection.find({ "testId": "123", "subjects.subjectName": "Maths", "subjects.testDetails.testNumber": "0002" }).toArray(function (err, data) {}..

But it will return entire TestId 123 document anyone help me. Thanks

2

2 Answers 2

0

Will be available

db.collection.aggregate([
          {$unwind : '$subjects'},
          {$project : {'_id': 0 , 'array' : '$subjects.testDetails'}},
          {$unwind : '$array'},
          {$match: {'array.testNumber' : '0002' }}
])
Sign up to request clarification or add additional context in comments.

Comments

0

With a find you always return a whole document, so you need to add a projection to only show what you need.

By the way in your find filter there is an error, because if you want to filter only collections with a particular subjects.subjectName and subjects.testDetails.testNumber you need to use $elemMatch (https://docs.mongodb.com/manual/reference/operator/query/elemMatch/). If you don't do this it will return all document where in the subjects array there is one element with the first property and another one with the second property.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.