Ask for advice on a mongo array query?

  mongodb, question

Talbe name: server_groups, for example, there are the following two data, and the field iplist is an array. There are multiple ranges stored in it. I want to check whether a number falls within this range. If i query 150 falls into the first record and the first array, then the first record will be returned. I query 750 falls into the second record, the second array. How to write this query statement? Ask for advice

{
 name:“111”,
 iplist:[
 {
 “start” : 100,
 “end” : 200
 },
 {
 “strat” : 500,
 “end” : 700
 }
 ]
 },
 {
 name:“111”,
 iplist:[
 {
 “start” : 300,
 “end” : 400
 },
 {
 “strat” : 800,
 “end” : 1000
 }
 ]
 }

First you need the appropriate index:

db.foo.createIndex({
 "iplist.start": 1,
 "iplist.end": 1
 });

Secondly, the index helps you find qualified documents, but not qualified array elements. If you need this element, use projection to find the required element:

db.foo.find({
 iplist: {
 $elemMatch: {
 start: {
 $lt: 150
 },
 end: {
 $gt: 150
 }
 }
 }
 }, {
 "iplist.$": 1
 });