1

How to replace only not sent null fields.

My Product Instance:

Product p1 = new Product(){ Name : "Apple", Money: 2 };

My Document:

{  
   "Id" : 1
   "Name" : "Apppple",
   "Money" : 3,
   "Color" : "Red"
}

I runned this code:

var _filterDef = Builders<Product>.Filter.Eq(x => x.Id, 1);
ProductCollection.ReplaceOne(_filterDef, p1);

Result: Red named field is null...

{  
   "Id" : 1
   "Name" : "Apple",
   "Money" : 2,
   "Color" : null
} 

I Want to Result: Red named field is not null

{  
   "Id" : 1
   "Name" : "Apple",
   "Money" : 2,
   "Color" : "Red"
}
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Biletbak.com
  • 409
  • 5
  • 14

2 Answers2

2

Either you send the entire document as a update or you use UpdateOne for updating fields selectively.

var _filterDef = Builders<Product>.Filter.Eq(x => x.Id, 1);
var update = Builders<Product>.Update.Set("Name", "Apple").Set("Money", 2);
ProductCollection.UpdateOne(_filterDef, update );

More examples here https://docs.mongodb.com/getting-started/csharp/update/

s7vr
  • 73,656
  • 11
  • 106
  • 127
  • Np. I don't think so when using driver directly. You may find some object modelling frameworks which will removes this interaction and directly map your model into mongo db documents but I don`t have any names. – s7vr Apr 25 '17 at 20:32
1

It looks like you're trying to update the document rather than replace it. In that case use the update operation documented here. You'll need to use the "$set" operator as in the example in the documentation.

joseph07
  • 441
  • 4
  • 2