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

chridam
  • 100,957
  • 23
  • 236
  • 235
Manihtraa
  • 968
  • 3
  • 12
  • 28
  • 1
    from [https://docs.mongodb.com/manual/reference/method/db.collection.find/] (find): Selects documents in a collection or view and returns a cursor to the selected documents. You should use project after find – Luca Rasconi Feb 09 '18 at 08:12
  • Already been asked and answered here: https://stackoverflow.com/questions/36229123/return-only-matched-sub-document-elements-within-a-nested-array –  Feb 09 '18 at 10:17

2 Answers2

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.

Mauro Piccotti
  • 1,807
  • 2
  • 23
  • 34
0

Will be available

db.collection.aggregate([
          {$unwind : '$subjects'},
          {$project : {'_id': 0 , 'array' : '$subjects.testDetails'}},
          {$unwind : '$array'},
          {$match: {'array.testNumber' : '0002' }}
])
Spz Sot
  • 3
  • 3