gpt4 book ai didi

mongodb - 在 MongoDB 中查询一个 ArrayPosition

转载 作者:可可西里 更新时间:2023-11-01 10:31:36 25 4
gpt4 key购买 nike

我有一个这样的集合:

> db.nodes.find()  
{ "_id" : ObjectId("534d44e182bee8420ace927f"), "id" : "59598841", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7346094, 52.371738 ] } }
{ "_id" : ObjectId("534d44e182bee8420ace9280"), "id" : "59598842", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7343616, 52.3718121 ] } }
{ "_id" : ObjectId("534d44e182bee8420ace9281"), "id" : "59598845", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7331504, 52.372057 ] } }
{ "_id" : ObjectId("534d44e182bee8420ace9282"), "id" : "59835778", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7354137, 52.3711697 ] } }
{ "_id" : ObjectId("534d44e182bee8420ace9283"), "id" : "60409270", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7354388, 52.3735999 ] } }

现在我想查询坐标数组以找到具有最大 lon 值的文档。我该怎么做,我不知道:(

楚斯,安德烈

最佳答案

因此实际上获取数组的第一个值“lon”可能看起来并不明显,但使用聚合非常简单:

db.nodes.aggregate([
{ "$project": {
"_id": {
"_id": "$_id",
"id": "$id",
"created_by": "$created_by",
"geo": "$geo",
},
"coordinates": "$geo.coordinates"
}},
{ "$unwind": "$coordinates" },
{ "$group": {
"_id": "$_id",
"lon": { "$first": "$coordinates" }
}},
{ "$sort": { "lon": 1 } },
{ "$limit": 1 },
{ "$project": {
"_id": "$_id._id",
"id": "$_id.id",
"created_by": "$_id.created_by",
"geo": "$_id.geo",
}}
])

它给出了整个文档的最高值。或者,如果您只想要值:

db.nodes.aggregate([
{ "$unwind": "$geo.coordinates" },
{ "$group": {
"_id": "$_id",
"lon": { "$first": "$geo.coordinates" }
}},
{ "$group": {
"_id": null,
"lon": { "$max": "$lon" }
}}
])

关于mongodb - 在 MongoDB 中查询一个 ArrayPosition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23102546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com