如何基于数组元素向mongoDB集合的文档添加新字段



我的mongoDB集合中有以下形状的文档:

{
"_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"
}

我想添加一个新的字段调用";"深度";基于几何坐标阵列的第三个元素。

以下是我目前所拥有的:

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

但它只给了我字符串,而不是第三个值。

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

但我想要的是

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

您可以使用聚合更新来允许使用$arrayElemAt,如下所示:

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

示例

相关内容

  • 没有找到相关文章

最新更新