Mahmoud Metwally
Mahmoud Metwally

Reputation: 990

Get specific fields from mongodb and return as object array

I have the following document:

"content": [
    {
        "_id": "5dbef12ae3976a2775851bfb",
        "name": "Item AAA",
        "itemImages": [
            {                 
                "_id": "5dbef12ae3976a2775851bfd",
                "imagePath": "https://via.placeholder.com/300",
                "imageTitle": "Test 300"
            },
            {
                "_id": "5dbef12ae3976a2775851bfc",
                "imagePath": "https://via.placeholder.com/250",
                "imageTitle": "Test 250"                 
            }
        ]
    }

and I am wondering if there is a way to return only the data in the array yet with the "name" and document "main _id" so that result set will be

        "itemImages": [
            {                 
                "_id": "5dbef12ae3976a2775851bfb",
                "name": "Item AAA",                    
                "imagePath": "https://via.placeholder.com/300",
                "imageTitle": "Test 300"
            },
            {
                "_id": "5dbef12ae3976a2775851bfb",
                "name": "Item AAA",                    
                "imagePath": "https://via.placeholder.com/250",
                "imageTitle": "Test 250"                 
            }
        ]

I've tried using mongodb find and aggregate functions but neither helped in retrieving the above results. Thanks for your help

Upvotes: 0

Views: 669

Answers (1)

Joe
Joe

Reputation: 28316

You should be able to get what you want with aggregation.

You'll need to:

  • unwind the array so there is a separate document for each element
  • use addFields to add the _id and name to the element
  • group to reassemble the array
  • project to get just the field you want

This might look something like:

db.collection.aggregate([
     {$unwind:"$itemImages"},
     {$addFields: {
           "itemImages._id":"$_id",
           "itemImages.name":"$name"
     }},
     {$group:{_id:"$_id", itemImages:{$push:"$itemImages"}}},
     {$project:{itemImages:1,_id:0}}
])

Upvotes: 1

Related Questions