mongodb 里面明明有$regex 关键字

mongodb 里面明明有$regex 关键字,但是在这里的cond 里面使用却报错了

db.getCollection('test_class')
.aggregate( [ {
  $project: {
    "className": 1,
    "students": {
      $filter: {
        input: "$students",
        as: "students",
        cond: {
          $and: [
            {
              $regex: [ "$$students.name",
                  "laoli"]
            }]
            }
          }
          }
          }
          } ] )

确认你mongodb的版本,如果是4.2以上的需要使用$regexMatch,示例代码

db.tmpAll.aggregate([
    { "$group": {
        "_id": {
            "BrandId": "$BrandId",
            "SessionId": "$SessionId"
        },
        "widget_count": {
            "$sum": { 
                "$cond": [
                    {
                        "$and": [ 
                            { "$eq": ["$Method", "POST"] },
                            { "$regexMatch": { 
                                "input": "$Url",
                                "regex": /widget/
                            } } 
                        ]
                    }, 1, 0
                ]                     
            }
        },
        "session_count": { "$sum": 1 }
    } },
    { "$group": {
        "_id": "$_id.BrandId",
        "create_widget": { "$sum": "$widget_count" },
        "distinct_session": { "$sum": "$session_count" }
    } }
]);