简体   繁体   English

MongoDB聚合以查询int64

[英]MongoDB aggregate to query int64

Let say my mongodb data store some data with int 假设我的mongodb数据使用int存储一些数据

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

Now i would like to query aggregate with regex those num start with 85, how do i do this with aggregate function? 现在我想用正则表达式查询聚合,那些以85开头的数字,我该如何使用聚合函数呢?

$substr can be used in a $project stage to convert the num to a string value. $ substr可以在$ project阶段中使用,以将num转换为字符串值。 You can then have a $match stage with the regex. 然后,您可以使用正则表达式进入$ match阶段。

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 . 继续这样做,直到达到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: 正如其他人已经指出的那样,可以使用$ substr来完成到字符串的转换,但是过滤所需的只是一个标准的equals比较:

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
    }
}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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