Ask a question about a mongo array query?

talbe name: server_groups, for example, has the following two pieces of data, and the field iplist is an array. There are multiple ranges stored in it, and I want to check whether a number falls within this range. If I query 150 and it falls into the first array of the first record, then I return the first record. My query 750 falls in the second record, in 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
        }
    ]
}
Jul.16,2021

first you need an appropriate index:

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

the secondary index helps you find documents that match the criteria, but array elements that do not. If you need this element, use projection to find the desired element:

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