How to ignore NULL values using myObject.ToBsonDocument

1,974 views
Skip to first unread message

Jürgen Stolz

unread,
Sep 18, 2015, 6:48:35 AM9/18/15
to mongodb-user
Hi,

if I store content in the mongodb I want to ignore NULL values. Some short code snippets

The class I want to store
    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Info { get; set; }
    }

I create a user, the parameter Info is not used
    private void InsertUser()
    {
        User user = new User() { FirstName = "John", LastName = "Doe"};
        Task task = DatabaseMongo.Insert_User(user);
    }

I create a BsoDocument and insert the content
....
{
  var mongoConnStr = MongoUrl.Create(connectionString);
  mongoClient = new MongoClient(mongoConnStr);
  mongoDatabase = mongoClient.GetDatabase("mongo_tut_1");
}
....
    public async static Task Insert_User(User user)
    {
        var collection = mongoDatabase.GetCollection<BsonDocument>("user");
        BsonDocument bsonDocument = user.ToBsonDocument();
        await collection.InsertOneAsync(bsonDocument);
    }

Querying the mongo, I do not like the  "Info" : null
/* 1 */
{
    "_id" : ObjectId("55fbe823f305213b7c64a5f6"),
    "FirstName" : "John",
    "LastName" : "Doe",
    "Info" : null
}

If I use additional libraries like ServiceStack (or NewtonSoft) I could generate an json content without NULL content via configuration
  if (excludeNullValues)
  {
      JsConfig.IncludeNullValues = false;
  }
          
  string jsonString = userObject.SerializeToJson();

Is this with the daefault mongo possible too?
Mongo Ver. 3.0
c# driver
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="MongoDB.Bson" version="2.0.1" targetFramework="net45" />
  <package id="MongoDB.Driver" version="2.0.1" targetFramework="net45" />
  <package id="MongoDB.Driver.Core" version="2.0.1" targetFramework="net45" />
</packages>

Regards
Juergen

Craig Wilson

unread,
Sep 18, 2015, 8:39:57 AM9/18/15
to mongodb-user
You can use an attribute of in code configuration to ignore this null value. This is documented here: http://mongodb.github.io/mongo-csharp-driver/2.1/reference/bson/mapping/#ignoring-default-values.

Jürgen Stolz

unread,
Sep 20, 2015, 1:49:11 PM9/20/15
to mongodb-user
Thanks, for the hint (it is easy)
Jürgen
Reply all
Reply to author
Forward
0 new messages