MongoDB $ substr平等问题

时间:2018-09-24 15:32:21

标签: mongodb

{      
  "val1" : "abcdefghijk",
  "val2" : "abcdefzzzzz"
}

在聚合中对计算出的子字符串执行$eq时,该行为似乎无法正常工作。即使{ subMatch : true },上面的文档也会返回"abcdefg" != "abcdefz"。谁能指出我正确的方向?

db.getCollection('myCollection').aggregate([
  {"$project": {
    "val1":1,
    "val2":1,
    "val1Sub": { "$substr" : [ "$val1", 0, 7 ] },
    "val2Sub": { "$substr": [ "$val2", 0, 7] },
    "subMatch": { "$eq":["$val1Sub","$val2Sub"] }
    }
  },
  {"$match":{"subMatch": true}}
])

2 个答案:

答案 0 :(得分:1)

这是一个用例,其中$let运算符可以帮助以简洁的方式表达事物:

db.getCollection('myCollection').aggregate([{
    $addFields: {
        result: {
            $let: {
                vars: {
                    "val1SubVariable": { "$substr" : [ "$val1", 0, 7 ] },
                    "val2SubVariable": { "$substr" : [ "$val2", 0, 7 ] }
                },
                in: {
                    "val1Sub": "$$val1SubVariable",
                    "val2Sub": "$$val2SubVariable",
                    "subMatch": { "$eq": [ "$$val1SubVariable", "$$val2SubVariable" ] }
                }
            }
        }
    }
}, {
    $match: { "result.subMatch": true }
}])

还要注意,从MongoDB v3.6开始,如果您要做的只是过滤,则根本不需要$ project / $ addFields阶段。在下面查看基于$expr的版本:

db.getCollection('myCollection').aggregate([{
    $match: {
        $expr: {
            $eq: [
                { "$substr" : [ "$val1", 0, 7 ] },
                { "$substr" : [ "$val2", 0, 7 ] }
            ]
        }
    }
}])

答案 1 :(得分:0)

val1Subval2Sub在此阶段均未同样未定义。仅在阶段后定义

您可以添加第二个$project阶段来计算subMatch

db.getCollection('myCollection').aggregate([
  {"$project": {
    "val1":1,
    "val2":1,
    "val1Sub": { "$substr" : [ "$val1", 0, 7 ] },
    "val2Sub": { "$substr": [ "$val2", 0, 7] }
    }
  },
  {"$project": {
    "subMatch": { "$eq":["$val1Sub","$val2Sub"] }
  },
  {"$match":{"subMatch": true}}
])

或串联$substr

db.getCollection('myCollection').aggregate([
  {"$project": {
    "val1":1,
    "val2":1,
    "val1Sub": { "$substr" : [ "$val1", 0, 7 ] },
    "val2Sub": { "$substr": [ "$val2", 0, 7] },
    "subMatch": { "$eq":[
        { "$substr" : [ "$val1", 0, 7 ] },
        { "$substr": [ "$val2", 0, 7] }
    ] }
    }
  },
  {"$match":{"subMatch": true}}
])