0

I'm trying to deep query and retrieve specific fields from MongoDB, but unfortunately couldn't able to figure out the correct solution.

Document data:

[ {
   "_id": 39127198,
   "name": "Mike",
   "details": {
      "age": 25,
      "vehicles":[
         {"brand":"Chevrolet","model":"Silverado","plate":"AB11"}, 
         {"brand":"Jeep","model":"Cherokee","plate":"CG678"}
      ]
   }
}, {
   "_id": 39127198,
   "name": "Taylor",
   "details": {
      "age": 25,
      "vehicles": [
          {"brand":"GMC","model":"Sierra","plate":"748397"}
      ]
   }
} ]

My requirement: Return "vehicles" array alone for a specific player. Let's say for user "Mike" in this case.

Here is what I tried;

collection.find( {"name":"Mike"} )
          .project( {"details.vehicles" : 1, "_id": 0, "name": 0} )
          .toArray(function(err, result) { ... } )

collection.aggregate([
  { $match: { "name":"Mike" } },
  { $project: {"details.vehicles" : 1, "_id": 0, "name": 0} }
]).toArray(function(err, result) { ... } )

Here is what I get for the above code:

[
   {
     "details": {
       "vehicles": [
         {"brand":"Chevrolet","model":"Silverado","plate":"AB11"}, 
         {"brand":"Jeep","model":"Cherokee","plate":"CG678"}
       ]
     }
   }
]

Expected:

[
   {"brand":"Chevrolet","model":"Silverado","plate":"AB11"}, 
   {"brand":"Jeep","model":"Cherokee","plate":"CG678"}
]

I am using MongoClient. MongoDB shell version v4.2.1

prasad_
  • 12,755
  • 2
  • 24
  • 36
msg
  • 1,480
  • 3
  • 18
  • 27

2 Answers2

2

You can use $unwind and $replaceRoot stages to achieve this :

db.collection.aggregate([
  {
    $match: {
      "name": "Mike"
    }
  },
  {
    $unwind: "$details.vehicles"
  },
  {
    $replaceRoot: {
      newRoot: "$details.vehicles"
    }
  }
])

Will output exactly what you need. Hope it helps

matthPen
  • 4,253
  • 1
  • 16
  • 16
0

The query:

db.vehi.aggregate( [ 
  { $match: { "name":"Mike" } },
  { $project: { "vehicles": "$details.vehicles", "_id": 0 } }
] ).next().vehicles

The exact output:

[
        {
                "brand" : "Chevrolet",
                "model" : "Silverado",
                "plate" : "AB11"
        },
        {
                "brand" : "Jeep",
                "model" : "Cherokee",
                "plate" : "CG678"
        }
]


- OR -

This also gets the same result:

db.vehi.find( 
  { "name" : "Mike" }, 
  { "details.vehicles" : 1, _id : 0 }
 ).next().details.vehicles
prasad_
  • 12,755
  • 2
  • 24
  • 36