0
votes

How can we get subfield from a collection using aggregation framework? Example,

Actual Document

    {
                "_id" : ObjectId("5c50589b4152f513f95809f2"),
                "Address" : [
                                {
                                                "AddressType" : "",
                                                "Line1" : "555 N Duke Street",
                                                "Line2" : "",
                                                "Line3" : "",
                                                "Area" : "AM-East Area",
                                                "City" : "Lancaster",
                                                "geoCode" : "Americas",
                                                "District" : "",
                                                "State" : "PA",
                                                "Country" : "United States",
                                                "PostalCode" : "17603",
                                                "County" : ""
                                }
                ]
}

Expected Result

{
“Line1” : “555 N Duke Street”
}

I used below pipeline and got this result(array of the field value):

    “Line1” : [
                "555 N Duke Street "
]



Pipeline = [
{"$project" : { 'AddressLine1' : "$Address.Line1" }
},
             {'$out' : "associationTransformed"
                              }
              ]
1

1 Answers

0
votes

If Address(Actual Document) Array contain multiple embedded document then your query is right.

Otherwise, use

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        Line1: "$Address.Line1"
      }
    }
  }, 
  { $unwind: '$Line1'}
])

or If you don't like $unwind stage.

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        Line1: { $arrayElemAt: [ "$Address.Line1", 0 ] }
      }
    }
  }
])