Create new field (domain) in collection with only the domain part of an email address

Hello,
I have lots of records in a collection. Each one of these records contains an email address. Now I would like to extract the domain part of an email address and save it in a new field called domain. (for each record) How can I do that?

I tried this code, but received the error:
MongoServerError: $arrayElemAt’s first argument must be an array, but is object

code

db.leads.update(
  {}, 
  [
    {
      $set: {
        domain: {
          $arrayElemAt: [
            {
              $regexFind: {
                input: "$email",
                regex: /@(.+)$/
              }
            },
            1
          ]
        }
      }
    }
  ],
  { multi: true } 
);

Thanks!

I cloned the email field with the new lable domain.
So now it looks like this:

email: “a@b.com
domain: “a@b.com

Now, I tried to cut off the domain part of each domain field with the following code snippet:

db.leads.updateMany(
  {}, 
    {
      $set: {
        domain: {
          $regexFind: {
            input: "$domain",
            regex: /@([a-zA-Z0-9.-]+)$

          }
        }
      }
    },

  ],
  
);

It sould update the domain field with the regexed value of the field, right??

Unfortunately,. I get the following error:

Error: clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:……)} could not be cloned. at Object.serialize (node:v8:371:7)

Why is that?

I have it!

db.leads.aggregate([
   {$project: 
      {
         firstname:1,
         lastname:1, email:1, phone:1, tdl:1,__v:1, createdAt:1, updatedAt:1,
         domain:{$arrayElemAt:[{$split:["$domain", "@"]}, 1]}
      }
   },
   {$out:"leads"}
 ]);

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.