How to optimize MongoDB query with both $gt and $lte?

后端 未结 4 1965
后悔当初
后悔当初 2021-02-07 23:53

I have the following query that is kind of like a reverse range lookup:

db.ip_ranges.find({ $and: [{ start_ip_num: { $lte: 1204135028 } }, { end_ip_num: { $gt: 1         


        
4条回答
  •  星月不相逢
    2021-02-08 00:10

    According to the Ip2location website, one can achieve fast queries on ip addresses with mongodb without the range query. Create just one index on mongodb { ip_to: 1 }, and query the ip with:

    db.collection_name.find({ ip_to: { $gte : ip_integer } }).sort({ ip_end: 1 }).limit(1)
    

    With this config I got 1ms query time with a 6 million document collection.

提交回复
热议问题