skywalker2909
skywalker2909

Reputation: 1686

How to not insert a field in mongodb if it is null?

I don't want mongodb to create a date/time field, if i am passing a null value, the code below works for all non-date types but fails for the date type. It creates a date/time field with a null value instead. This is a code snippet of my bsondocument below

   {"stringfield", stringfield= string.IsNullOrWhiteSpace(stringfield)?null:stringfield},
   {"datetime", datetime.HasValue == false ?null:datetime}

Note: I am not making use of any classes to map mongodb fields to properties, rather directly creating a bsondocument and inserting that document in mongodb.

I tried using the Convention pack with the following code below, but i guess that applies only when i create classes to map mongofields to properties?

        var pack = new ConventionPack();
        var ignoreIfNull = new IgnoreIfNullConvention(true);
        pack.Add(ignoreIfNull);
        ConventionRegistry.Register("ignoreNulls", pack, t => true);

Upvotes: 4

Views: 8599

Answers (2)

skywalker2909
skywalker2909

Reputation: 1686

Update: As requested by people in the comments, i am including a proper answer to the solution with the link as a reference.

Below is the code snippet that sets the date field in a mongodb document if the nullbale 'mydate' parameter has a value, or simply does not create the field if its null or empty.

{ "date", mydate.Value, mydate.HasValue }

And below is the reference link that contains the answer from @Craig Wilson at the mongodb-csharp google group as i had posted this same question over there too.

How to not insert a field in mongodb if it is null?

Upvotes: 1

wdberkeley
wdberkeley

Reputation: 11671

If you don't want to insert the field with a null value, don't insert it with a null value. Instead, don't put the field in the document at all. Meaning, instead of this:

db.stuff.insert({ "a" : 1, "b" : null })

do this

db.stuff.insert({ "a" : 1 })

It might not be a problem for you to insert null values of fields anyway, since they behave like missing values for queries:

> db.test.drop()
> db.test.insert({ "a" : 1 })
> db.test.insert({ "a" : 1, "b" : null })
> db.test.count({ "b" : null })
2

Upvotes: 1

Related Questions