Mongodb find comparing array elements

后端 未结 3 1738
说谎
说谎 2021-01-14 05:59

I have a collection with about 200K documents like this:

db.place.find()[0]
{
    \"_id\" : ObjectId(\"5290de1111afb260363aa4a1\"),
    \"name\" : \"place X\         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 06:50

    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.

    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]]]
    } } } } );
    

    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.

提交回复
热议问题