Date inserted as STRING but should be DATE or TIMESTAMP

I am storing my Data to Mongo Atlas Cloud using PHP Library.

All Data is inserted properly, but i am facing issue with date type. Sample of my data is:

    "type" : "search",
"date_added" : "2020-10-12 11:21:36",
"product_data" : {
   "name" : "red floral dress",
   "total_products" : "178"

In above sample, total_products is type STRING but should be INT and date_added is type STRING but should be type DATE or timestamp

While passing data from PHP (in JSON format) to MongoDB, it automatically convert everything to STRING.

What i can do to keep the data type Same as i want.

I am using PHP 7.2, so how can i define a schema for my Collection.

One last thing, I have a collection of size 1.5 GB , is there any way to manage all data according to my Schema?


Hello @Hashir_Anwaar, can you tell how you are inserting the JSON data? What is the code and the data you are inserting?

My Controller Code:

$mongoData = array(
          'type' => $post['type'],  *//STRING TYPE*
          'product_data' => $post['event_data'], *//Object*
          'date_added' => $post['event_time'] *//STRING TYPE, But should be date/timestamp*

        $mongoCollection = 'myCollection';

        $this->mongodb->insert($mongoCollection, $mongoData);

My MongoDB Library Code is:

$insert = $collection->insertOne($data);

Here is post explaining how you can insert date object into a MongoDB document: Inserting and retriving dates and timestamps in mongodb using PHP

Thanks for the link, but when i use that approach $utcdatetime = new MongoDB\BSON\UTCDateTime($orig_date*1000); it change my date and also store it as date type in format 2021-01-25T07:25:59.765+00:00

For example, if my date is today’s date, then multiplying it with 1000 cause date change…

Also, type is Date but what if i want to store it as type Timestamp?

Thanks a lot

Can you tell why you are multiplying with 1000?

bcz of the example… :smirk: but i dnt need that tough :stuck_out_tongue:

just need to save it as TimeStamp type now

Hi @Hashir_Anwaar

If you are referring to the BSON type Timestamp, don’t use that, stick with the Date type. If you are not then ignore the rest of this response.

A Date will give resolution down to the millsecond, a Timestamp is at second resolution with an ordinal counter. Primarily the Timestamp is used in a Mongodb replicaset members oplog.

BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where:

  • the most significant 32 bits are a time_t value (seconds since the Unix epoch)
  • the least significant 32 bits are an incrementing ordinal for operations within a given second.


The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

1 Like