我有一个这样的集合:
> 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 ] } }
现在我想查询coordinates-array以找到具有最大lon-value的文档。 我怎么能这样做,我不知道:(
Tschüss,Andre
答案 0 :(得分:2)
所以实际上得到数组的第一个值“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" }
}}
])
答案 1 :(得分:0)
尝试使用聚合框架
db.nodes.aggregate(
{ $unwind: "geo.coordinate" },
{ $group: { _id: { id: "$id"}, lon: { $first: "geo.coordinate" } } },
{ $group: { _id: null, maxval: { $max: "$lon" } } }
)
有关聚合的更多信息,请查看此处:http://docs.mongodb.org/manual/reference/operator/aggregation/