简体   繁体   中英

MongoDB aggregate to query int64

Let say my mongodb data store some data with int

  1. num: 850531015931
  2. num: 860338053336
  3. num: 859923992712

Now i would like to query aggregate with regex those num start with 85, how do i do this with aggregate function?

$substr can be used in a $project stage to convert the num to a string value. You can then have a $match stage with the regex.

Project Stage:

{
    $project:{
        numAsString: { $substr : ["$num", 0, -1 ] }
    }
}

Match Stage:

{
    $match : { numAsString: { $regex: /^85.*/ } }
}

Although this can be done by regexes, I would like to suggest an alternate method. The problem with regex is that it wont allow you to index elements. Hence as your collection size increases, your queries will become slower and slower.

You can just go for the basics and do the following checks

{$or: [
    {$and: [ {$gte: ['$num', 85] }, {$lte: ['$num', 85] } ]},
    {$and: [ {$gte: ['$num', 850] }, {$lte: ['$num', 859] } ]},
    {$and: [ {$gte: ['$num', 8500] }, {$lte: ['$num', 8599] } ]},
    {$and: [ {$gte: ['$num', 85000] }, {$lte: ['$num', 85999] } ]},
    {$and: [ {$gte: ['$num', 850000] }, {$lte: ['$num', 859999] } ]},
    {$and: [ {$gte: ['$num', 8500000] }, {$lte: ['$num', 8599999] } ]},
    {$and: [ {$gte: ['$num', 85000000] }, {$lte: ['$num', 85999999] } ]},
    {$and: [ {$gte: ['$num', 850000000] }, {$lte: ['$num', 859999999] } ]},
    {$and: [ {$gte: ['$num', 8500000000] }, {$lte: ['$num', 8599999999] } ]},
    {$and: [ {$gte: ['$num', 85000000000] }, {$lte: ['$num', 85999999999] } ]},
]}

Keep doing this till you reach the max possible value in num . Sorry for the ugly code, but it should run faster .

首先,您必须使用$ substr运算符将整数转换为字符串,而不是使用$ regex运算符执行$ match功能

db.collection.aggregate([{$project :{numstring : {$substr :["$number",0,12]}}},{$match :{"numstring":{$regex : /^8.5/}}}])

There's no point in using a regular expression in your specific case. As the others already pointed out the conversion to a string can be done using $substr but the all it takes for the filtering is a standard equals comparison:

db.collection.aggregate([{
    $addFields: {
        "firstTwoDigits": { // create a new field called "firstTwoDigits"
            $substr: ["$num", 0, 2] // extract the first two digits only
        }
    }
}, {
    $match: {
        "firstTwoDigits": "85" // simple filter
    }
}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM