Issue with transforming data

Hi,

I have the below document stored in one of my collections

"bookingLines" : [ 
        {
		    "BookingLines" : {
                "BookingLineCode" : "CNF146551_5",
                "BookingLine_id" : 86660727,
                "MarketKey" : "asia"
            }
        },
		{
			"BookingLines" : {
                "BookingLineCode" : "CNF146551_8",
                "BookingLine_id" : 86660728,
                "MarketKey" : "paris"
            }
		}
	]

And, I would like to transform this to something like below

"bookingLines" : [ 
        {
            "BookingLineCode" : "CNF146551_5",
            "BookingLine_id" : 86660727,
            "MarketKey" : "asia"

        },
		{

            "BookingLineCode" : "CNF146551_8",
            "BookingLine_id" : 86660728,
            "MarketKey" : "paris"
		}
	]

Could anyone please let me know how I can achieve using the aggregate pipeline options ?

Thanks,
Vinay

Hi @Vinay_Gangaraj,

Here is my starting point:

test:PRIMARY> db.coll.find().pretty()
{
	"_id" : ObjectId("5f8ee428867da8a9a949fb40"),
	"bookingLines" : [
		{
			"BookingLines" : {
				"BookingLineCode" : "CNF146551_5",
				"BookingLine_id" : 86660727,
				"MarketKey" : "asia"
			}
		},
		{
			"BookingLines" : {
				"BookingLineCode" : "CNF146551_8",
				"BookingLine_id" : 86660728,
				"MarketKey" : "paris"
			}
		}
	]
}

Here is my aggregation pipeline:

[
  {
    '$unwind': {
      'path': '$bookingLines'
    }
  }, {
    '$project': {
      'a.BookingLineCode': '$bookingLines.BookingLines.BookingLineCode', 
      'a.BookingLine_id': '$bookingLines.BookingLines.BookingLine_id', 
      'a.MarketKey': '$bookingLines.BookingLines.MarketKey'
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'bookingLines': {
        '$push': '$a'
      }
    }
  }
]

And here is the result I get:

{
	"_id" : ObjectId("5f8ee428867da8a9a949fb40"),
	"bookingLines" : [
		{
			"BookingLineCode" : "CNF146551_5",
			"BookingLine_id" : 86660727,
			"MarketKey" : "asia"
		},
		{
			"BookingLineCode" : "CNF146551_8",
			"BookingLine_id" : 86660728,
			"MarketKey" : "paris"
		}
	]
}

Enjoy,
Maxime.

2 Likes

Hi @MaBeuLux88,

Thanks for your response. But, I was able to solve it with below approach :slight_smile:

[{
    $project: {
        _id: 0,
        bookingLines: "$bookingLines.BookingLines",
    }
}]

Oh damn I didn’t know this would work on an array out of the box!
Awesome :muscle: !

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.