skip to Main Content

I am using mongo 4.2

I have a collection which has a string field which is supposed to be a date type.

I tried to use the follwoing to convert the field to a date type, but it runs forever:

db.report_device_audit.find({ ‘date’ : { ‘$type’ : ‘string’ }}
).forEach(function (doc) { doc.date = new Date(doc.date); //
convert field to date db.report_device_audit.save(doc); });

My thoughts then are to convert the field to a date type and put it into a new collection:

db.report_device_audit.aggregate( {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$date',
            timezone: 'America/New_York'
         }
      }
   }
} , 
    {
        $out : "report_device_audit_date"
    } 
);

The problem is that the new collection contains now only the date field.

How can I project all the other fields to the new collection?

Thanks,
Tamar

2

Answers


  1. Chosen as BEST ANSWER

    Found this quick and easy way:

    db.report_device_audit.update(
        {},
        [{
            $set: {
                "date":
                    { $convert: { input: "$date", to: "date" } },
            }
        }],
        { multi: true }
    )
    

  2. $project defines the returned fields either by including or excluding fields. In your case, you included the field date which automatically excludes all other fields beside _id if they are not specifically included.
    Since you want to convert a field while maintaining the rest of the document you should use the aggregation stage $addFields. Using the same field name which is already present will replace the current value.

    In addition, you can use $merge to merge the changes into the existing collection without the need to use a new one. The final result would look like this:

    db.report_device_audit.aggregate( [{
      $addFields: {
        date: {
          $dateFromString: {
            dateString: '$date',
            timezone: 'America/New_York'
          }
        }
      }
    }, 
    {
      $merge : {
        into: "report_device_audit"
      }
    } 
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search