Home > Software design >  $addField by regex condition with Mongo < 4.2
$addField by regex condition with Mongo < 4.2

Time:05-11

I have a mongoDB collection with the following objects:

{
name: "a",
email: "[email protected]"
},
{
name: "b",
email: "[email protected]"
},
{
name: "c",
email: "[email protected]"
}

I want to add to each document a field of true/false if the email address matches the /bestemail/ regex expression.

Meaning, for the current collection I would get:

{
name: "a",
email: "[email protected]",
matching: true
},
{
name: "b",
email: "[email protected]",
matching: true
},
{
name: "c",
email: "[email protected]",
matching: false
}

The main issue is that I have to work with mongo version 4.0.12 and so I cannot use $regexMatch (available from mongo 4.2)

I have tried using:

$addFields: {"matching": {$cond: [{$in: ["$email", [/bestemail/]]}, true, false]}}

but I get matching: false for all documents.

Thank you for the assistance!

CodePudding user response:

I hesitate to respond since I don't have access to a MongoDB server with version 4.0.12, but perhaps this will work. [I did look at the archived docs.]

db.collection.aggregate([
  {
    "$addFields": {
      "matching": {
        "$cond": [
          {
            "$gt": [
              { "$indexOfCP": [ "$email", "bestemail" ] },
              0
            ]
          },
          true,
          false
        ]
      }
    }
  }
])

Try it on the wrong server version at mongoplayground.net.

Example output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "email": "[email protected]",
    "matching": true,
    "name": "a"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "email": "[email protected]",
    "matching": true,
    "name": "b"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "email": "[email protected]",
    "matching": false,
    "name": "c"
  }
]
  • Related