0

My mongodb schema has a field of "double" data type. Sometimes, when there is no value for this field, mongo is storing it as 0.0 but I need it to store as null

My Schema:

db.createCollection("nulltest", {
    validator: { $jsonSchema: {
        bsonType: "object",
        properties: {
            "name": {
                bsonType: "string"
            },
            "salary": {
                bsonType: "double"
                }
            }}
        }} )

1. db.nulltest.insertOne({ "name": "abc", "salary": null }) - When inserted, schema validation fails (which is expected)

2. db.nulltest.insertOne({ "name": "abc", "salary": Number(null) }) - When inserted, stores as 0.0 ("salary" : 0.0)

3. db.nulltest.insertOne({ "name": "abc", "salary": Number() }) - When inserted, stores as 0.0 ("salary" : 0.0)

4. db.nulltest.insertOne({ "name": "abc", "salary": Number("null") }) - When inserted, stored as NaN ("salary" : NaN)

Question: How can I store null value in a field of double data type? ie: "salary": null

Thank you!

0

Update Schema to store two data type values in a field is to define it as array.

Updated schema:

db.createCollection("nulltest", {
    validator: { $jsonSchema: {
        bsonType: "object",
        properties: {
            "name": {
                bsonType: "string"
            },
            "salary": {
                bsonType: ["double", "null"]
                }
            }}
        }} )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.