JediJesus
JediJesus

Reputation: 329

Merge two fields into a new object field in mongodb

I'm using this code :

db.collection.updateMany({},[{ $set: {points: [ "$latitude", "$longitude" ] } },
                                       { $unset: [ "longitude", "latitude" ] }])

to create the points field based on Latitude/Longitude values, but i need to have a "label" on each of them so when i search then it shows something like below :

"points": 
 {
     [
       { 
         "latitude": -3.724404,
         "longitude": -38.557694
       }
     ]
 }

Any idea?

Upvotes: 1

Views: 660

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

If I understand it correct your documents look like this :

[
  {
    "_id" : 123,
    "latitude": -3.724404,
    "longitude": -38.557694
  },
  {
    "_id" : 456,
    "latitude": -3.724404,
    "longitude": -38.557694
  }
]

You can use this query :

db.collection.updateMany({}, [
  {
    $set: {
      points: [
        {
          latitude: "$latitude",
          longitude: "$longitude"
        }
      ]
    }
  },
  { $unset: ["longitude", "latitude"] }
]);

To get something like this :

[
  {
    "_id": 123,
    "points": [
      {
        "latitude": -3.724404,
        "longitude": -38.557694
      }
    ]
  },
  {
    "_id": 456,
    "points": [
      {
        "latitude": -3.724404,
        "longitude": -38.557694
      }
    ]
  }
]

But why do you need points as an array, instead it can be an object like this :

"points": {
      "latitude": -3.724404,
      "longitude": -38.557694
    }

Get it with almost the same query :

db.collection.updateMany({}, [
  {
    $set: {
      points: 
        {
          latitude: "$latitude",
          longitude: "$longitude"
        }
    }
  },
  { $unset: ["longitude", "latitude"] }
]);

Upvotes: 1

Related Questions