mongodb - Find document with closest integer value

前端 未结 2 1313
我在风中等你
我在风中等你 2020-11-30 11:15

Let\'s assume I have a collection with documents with a ratio attribute that is a floating point number.

{\'ratio\':1.437}

How do I write a

2条回答
  •  失恋的感觉
    2020-11-30 11:43

    I have another idea, but very tricky and need to change your data structure.

    You can use geolocation index which supported by mongodb

    First, change your data to this structure and keep the second value with 0

    {'ratio':[1.437, 0]}
    

    Then you can use $near operator to find the the closest ratio value, and because the operator return a list sorted by distance with the integer you give, you have to use limit to get only the closest value.

    db.places.find( { ratio : { $near : [50,0] } } ).limit(1)
    

    If you don't want to do this, I think you can just use @JohnnyHK's answer :)

提交回复
热议问题