Home > database >  Transform mongo arrarys
Transform mongo arrarys

Time:10-21

I have a collection, which contains documents like

{
   "_id": ObjectId("60f561eb0d022a4c614966c1"),
   "vehicleId": 288,
   "startTime": [
      ISODate("2021-06-19T13:00:19Z"),
      ISODate("2021-06-19T13:00:40Z")
   ],
   "odo": [0, 1116.0746443123298],
   "location": [
      { "type": "Point", "coordinates": [75.759973, 26.977889] },
      { "type": "Point", "coordinates": [75.771209, 26.97858] }
   ]
}

I want to change the location array so that the document looks like

{
   "_id": ObjectId("60f561eb0d022a4c614966c1"),
   "vehicleId": 288,
   "startTime": [
      ISODate("2021-06-19T13:00:19Z"),
      ISODate("2021-06-19T13:00:40Z")
   ],
   "odo": [0, 1116.0746443123298],
   "locations": [
      { loc: { "type": "Point", "coordinates": [75.759973, 26.977889] } },
      { loc: { "type": "Point", "coordinates": [75.771209, 26.97858] } }
   ]
}

that is, each entry becomes an object. I may want to do the same thing to odo and starttime.

I'm experimenting with aggregation pipelines, but I haven't found a way except using application code to read and transform the object.

I'd rather do it via a mongo-only way and not have use application and parse document by document, so any help with a mongo-only way would be much appreciated.

CodePudding user response:

Would be this one:

db.collection.aggregate([
  {
    $set: {
      location: "$$REMOVE",
      locations: {
        $map: {
          input: "$location",
          in: { loc: "$$this" }
        }
      }
    }
  }
])
  • Related