How to use [BsonIgnoreIfNull] for an integer Type

786 views
Skip to first unread message

Adrian Lopez

unread,
Feb 2, 2016, 1:21:23 PM2/2/16
to mongodb-user
Hi, there's any way to use  [BsonIgnoreIfNull]]stament in a int field of a model? Since C# don't allow to have null values for int variables, I cant figure out. Regards.

 public class MyModel
{

[BsonIgnoreIfNull
 public int field1 get;set;}

}

Robert Stam

unread,
Feb 2, 2016, 4:18:25 PM2/2/16
to mongod...@googlegroups.com
[BsonIgnoreIfNull] is meant to be used with reference types (types that can have a null value).

You can use [BsonIgnoreIfDefault] with int values if you want. If the int value is 0 it won't be serialized.

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/1b94c327-5937-45a8-8756-581e4fe89d8d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Robert Stam

unread,
Feb 2, 2016, 4:20:24 PM2/2/16
to mongod...@googlegroups.com
You can also use [BsonIgnoreIfNull] with nullable ints:

    public class C
    {
        [BsonIgnoreIfNull]
        public int? F { getset; } // int? instead of int
    }
F won't be serialized if it is null (i.e. HasValue is false).

Adrian Lopez

unread,
Feb 2, 2016, 10:25:52 PM2/2/16
to mongodb-user

Thank you Robert! I also realized that a numeric string is actually stored as integer by mongoDB.

Adrian Lopez

unread,
Feb 2, 2016, 10:26:05 PM2/2/16
to mongodb-user

Robert Stam

unread,
Feb 3, 2016, 7:33:30 AM2/3/16
to mongod...@googlegroups.com
Not sure what you mean by your last comments.

Strings are stored as strings (even if they happen to contain characters that look like a number).

On Tue, Feb 2, 2016 at 9:26 PM, Adrian Lopez <adrian...@gmail.com> wrote:

Thank you Robert! I also realized that a numeric string is actually stored as integer by mongoDB.

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
Reply all
Reply to author
Forward
0 new messages