How can I insert null in date data type of MongoDB

q1) pls tell how can I do it using mongo compass and also from mongo shell in date datatype

for ex we keep date in this formate , what i have to do is, i want to keep it null
and want to filter it in c# using mongo driver.

{
  "dateFrom": {
        "$date": {
            "$numberLong": "1569888000000"
        }
    }
    }
}

Hello, @Rajesh_Yadav!
If I understood you correctly, you want to have property ā€˜dā€™ in the document, that would contain integer representation of date or null, if date is not provided?
If so, consider this mongo shell example:

const intDate = Date.now();
db.your_collection.insert({ d: intDate });
db.your_collectoin.insert({ d: null });

You can also add some validation for ā€˜dā€™ property:

db.createCollection('your_collection', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: [ 'd' ],
      properties: {
        d: {
          bsonType: ['double', 'null'],
        },
      },
    },
  },
});

With the above validator, you will be able to insert either int or null as a value for property ā€˜dā€™. Property ā€˜dā€™ is required (must always be present in any inserted document).

1 Like