Search code examples
mongodbaggregation

How can i swipe keys in mongodb while creating aggregation pipeline


I want to combine 3 flows which is present in mongodb which has 3 documents. I want to combine on the bases of src_ip , dst_ip, src_port, dst_port, protocol but my main problem is the one the flow is in reversed order how can i swipe it or i can create a hash which does not get affected on position change.

[{
 $match: {
  $or: [
   {
    _id: ObjectId('64227c692063fe9b27582cb1')
   },
   {
    _id: ObjectId('64227c692063fe9b27582ded')
   },
   {
    _id: ObjectId('64227cc62063fe9b2c3356f5')
   }
  ]
 }
}, {
 $sort: {
  timestamp: -1
 }
}, {
 $group: {
  _id: {
   sourceIPv4Address: '$sourceIPv4Address',
   destinationIPv4Address: '$destinationIPv4Address',
   sourceTransportPort: '$sourceTransportPort',
   destinationTransportPort: '$destinationTransportPort',
   protocol: '$protocol'
  },
  arr: {
   $addToSet: '$tcpFlags'
  }
 }
}]

This is the aggregation pipeline i tried. Also giving sample. enter image description here

enter image description here

ALSO,I AM ASKED NOT TO CREATE LOGIC WITH PRIVATE IP AND PUBLIC IP ADDRESSES CHECK.


Solution

  • Before grouping, create a new field that contains a sorted array of both addresses, then group by the new array. Since it is sorted, it will be the same no matter which is the source/destination.

    {$addFields: {
        addresses:{
           $sortArray:{ 
               input: [ '$sourceIPv4Address', '$destinationIPv4Address' ],
               sortBy: 1
           }
        }
    }}