MongoDB找到比较数组元素 [英] Mongodb find comparing array elements
问题描述
我有一个约有200,000个文档的收藏集,如下所示:
I have a collection with about 200K documents like this:
db.place.find()[0]
{
"_id" : ObjectId("5290de1111afb260363aa4a1"),
"name" : "place X",
"center" : [x, y]
}
现在,我正在尝试查询中心Y大于X的位置,并且遇到以下问题:
Now I`m trying to query for the places where the center Y is greater then X, and having the following problem:
> db.place.find({'center.0':{'$gt':center.1}}).count()
Sat Nov 23 14:42:01.556 JavaScript execution failed: SyntaxError: Unexpected number
有任何提示吗? 预先感谢
Any hints? Thanks in advance
推荐答案
由于您每次碰巧都具有确切的字段格式(圆圈是两个元素的数组),因此可以在聚合框架中将其转换为两个字段,然后进行比较将它们放在一起进行投影,然后进行匹配以仅返回满足您的第二个数组元素大于第一个数组元素要求的元素.
Because you happen to have exact format of the field every time (circle is a two element array) you can transform it in aggregation framework into two fields and then compare them in a projection, and match to get back just the elements satisfying your requirement of second array element being greater than first array element.
db.place.aggregate( [
{ $unwind : "$center" },
{ $group : { _id : "$_id",
centerX : {$first:"$center"},
centerY : {$last:"$center"}
} },
{ $project : { YgtX : { $gt : [ "$centerY", "$centerX" ] } } },
{ $match : { YgtX : true } }
] );
现在,如果您的数组是任意一对数字值,则可以使用上面的值.
Now, if your array was an arbitrary pair of numerical values, then you can use the above.
您在评论中说,您的一对代表坐标(纬度,长)-请记住,在MongoDB中,坐标对始终为存储为经度长的纬度-如果您实际的x,y值是在平坦(而不是球形)位置上坐标的,可以通过单个地理空间查询找到Y坐标大于X坐标的所有文档:
You said in comments that your pair represented coordinates (lat, long) - keep in mind that in MongoDB coordinate pairs are always stored as long, lat - if your actual x, y values were coordinates in on a flat (as opposed to spherical) place, you could find all the documents that had Y coordinate greater than X coordinate with a single geospatial query:
db.place.find( { center : { $geoWithin : { $geometry : {
type:"Polygon",
coordinates:[[[50,50],[-50,50],[-50,-50],[50,50]]]
} } } } );
上面的查询假设您的坐标系沿X和Y从-50到50,并且在三角形中找到代表所有Y> = X的坐标的所有点.
The above query assumes that your coordinate system goes from -50 to 50 along X and Y and it finds all points in the triangle that represents all coordinates having Y >= X.
这篇关于MongoDB找到比较数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!