'How to add a new field to mongoDB collection's documents based on an array element

I have documents of the following shape in my mongoDB collection:

{
        "_id" : ObjectId("622afbb16c5bba83829e8033"),
        "type" : "Feature",
        "properties" : {
                "mag" : 0.6,
                "place" : "6km NW of The Geysers, California",
                "time" : NumberLong("1370255770900"),
                "updated" : NumberLong("1370256367681"),
                "tz" : -420,
                "url" : "http://earthquake.usgs.gov/earthquakes/eventpage/nc72001595",
                "detail" : "http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/nc72001595.geojson",
                "cdi" : null,
                "mmi" : null,
                "alert" : null,
                "status" : "AUTOMATIC",
                "tsunami" : null,
                "sig" : 6,
                "net" : "nc",
                "code" : "72001595",
                "ids" : ",nc72001595,",
                "sources" : ",nc,",
                "types" : ",general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,",
                "nst" : null,
                "dmin" : 0.01796631,
                "rms" : 0.05,
                "gap" : 205.2,
                "magType" : "Md",
                "type" : "earthquake",
                "iso_date" : ISODate("2013-06-03T10:36:10.900Z"),
                "types_as_array" : [
                        "general-link",
                        "geoserve",
                        "nearby-cities",
                        "origin",
                        "phase-data",
                        "scitech-link"
                ]
        },
        "geometry" : {
                "type" : "Point",
                "coordinates" : [
                        -122.8173,
                        38.8115,
                        9.4
                ]
        },
        "id" : "nc72001595"
}

And I would like to add a new field call "depth" based on the 3rd element of the geometry.coordinates array.

Here is what I have so far:

db.earthquakes.updateMany({}, {$set:{"depth":"$geometry.coordinates.2"}} )

But it only gives me the string and not the 3rd value.

"id" : "nc72001620",
"depth" : "$geometry.coordinates.2"

But what I would like to get is

"id" : "nc72001620",
"depth" : "9.4"


Solution 1:[1]

You can use an aggregation update to be allowed to use $arrayElemAt like this:

db.collection.update({},
[
  {
    $set: {
      "depth": {
        "$arrayElemAt": [
          "$geometry.coordinates",
          2
        ]
      }
    }
  }
])

Example here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J.F.