代码之家  ›  专栏  ›  技术社区  ›  Piyush Jain

如何在mongodb中找到整数值的$regex?

  •  2
  • Piyush Jain  · 技术社区  · 6 年前

    我有以下收藏。

    [{
      _id: ObjectId("5b17ab5489264c2df61ed2d6"),
       amount: 12514545
    }]
    

    125 并获取以下文档。

    我试过这个,但不起作用:

    db.collection.find({
      amount: {
        $regex: 125
      }
    })
    

    如果可以通过聚合查询来完成就更好了。

      Test.aggregate([
        { "$match": { "$or": [
        { "amount": { parseInt(searchString) }},
        { "firstName": { "$regex": searchString }}
      ] } }
      ])
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   JohnnyHK    6 年前

    你可以用 $where

    db.test.find({$where: 'this.amount.toString().match("125")'})
    

    但你不能用 总的来说 $match .

    amount 在用于正则表达式搜索的每个文档中。

    {
      _id: ObjectId("5b17ab5489264c2df61ed2d6"),
       amount: 12514545,
       amountString: '12514545'
    }
    

    然后您可以像搜索任何其他字符串字段一样搜索它:

    Test.aggregate([
      { "$match": { "$or": [
        { "amountString": { "$regex": searchString }},
        { "firstName": { "$regex": searchString }}
      ] } }
    ])