Home > OS >  Mongodb: Merge nested objects based on common identifier
Mongodb: Merge nested objects based on common identifier

Time:04-24

I have 3 objects like this

{"_id":{"$oid":"625f0e73b1d7269de9ebdaeb"},
"Type":"scalar",
"Temperature":22.79,
"Vibration":{"A-P2P":{"X":85},"Z2P":{"X":43},"Crest":{"X":417}},
"Timestamp":1650396787,
"GatewayId":"0df07c53","MeasDetails":{"G-range":4,"Trigger":4,"Id":51940}}

{"_id":{"$oid":"625f0e73b1d7269de9ebdaeb"},
    "Type":"scalar",
    "Temperature":22.79,
    "Vibration":{"A-P2P":{"Y":85},"Z2P":{"Y":43},"Crest":{"Y":417}},
    "Timestamp":1650396787,
    "GatewayId":"0df07c53","MeasDetails":{"G-range":4,"Trigger":4,"Id":51940}}

{"_id":{"$oid":"625f0e73b1d7269de9ebdaeb"},
    "Type":"scalar",
    "Temperature":22.79,
    "Vibration":{"A-P2P":{"Z":85},"Z2P":{"Z":43},"Crest":{"Z":417}},
    "Timestamp":1650396787,
    "GatewayId":"0df07c53","MeasDetails":{"G-range":4,"Trigger":4,"Id":51940}}

Everything else is redundant, except for keys X, Y, Z in Vibration key. I want to merge this into a single object like this

{"_id":{"$oid":"625f0e73b1d7269de9ebdaeb"},
    "Type":"scalar",
    "Temperature":22.79,
    "Vibration":{"A-P2P":{"X":85, "Y":85, "Z":85},"Z2P":{"X":43, "Y":43, "Z":43},"Crest":{"X":417, "Y":417, "Z":417}},
    "Timestamp":1650396787,
    "GatewayId":"0df07c53","MeasDetails":{"G-range":4,"Trigger":4,"Id":51940}}

CodePudding user response:

Query

  • query assumes that you only have Crest/A-P2P/Z2P and only X/Y/Z
  • group and merge objects creating one merged object for each of them
  • set/unset to fix the structure

Playmongo

aggregate(
[{"$group": 
   {"_id": "$MeasDetails.Id",
    "A-P2P": {"$mergeObjects": "$Vibration.A-P2P"},
    "Z2P": {"$mergeObjects": "$Vibration.Z2P"},
    "Crest": {"$mergeObjects": "$Vibration.Crest"},
    "Type": {"$first": "$Type"},
    "Temperature": {"$first": "$Temperature"},
    "Timestamp": {"$first": "$Timestamp"},
    "GatewayId": {"$first": "$GatewayId"}}},
 {"$set": 
   {"Vibration": {"A-P2P": "$A-P2P", "Z2P": "$Z2P", "Crest": "$Crest"}}},
 {"$unset": ["A-P2P", "Z2P", "Crest"]}])
  • Related