0

I want If document exists Update only one property, If does not exist insert a document not only with one property (with all properties) in mongo,

for example:

        var customer = new Customer
        {
            Name="David",
            Family="Green",
            CustomerId="12",
            Gender="male"

        };

var filter = Builders<Customer>.Filter.Where(s => s.CustomerId == customer.CustomerId);

var updateDefination =
            (Builders<Customer>.Update.Set(s => s.Name, customer.Name));

var options=new UpdateOptions
            {
                IsUpsert = true,

            };

  MongoHelper.GetCollection<Customer>().UpdateOne(filter, updateDefination,options);

How can I say if Customer with that id does not exist, insert customer object with all that properties.

someone
  • 535
  • 4
  • 14
  • Why don't you use `Count()` to see if the Customer already exists, and then `if`/`else` to assert whether to add/insert. There's [another answer here](https://stackoverflow.com/a/6411783/6240567) that might help with finding the `Count()` of records – Geoff James Dec 02 '17 at 12:09
  • @GeoffJames tnx for your comment, Yes there is these alternatives but I wonder if there is more cleaner way without if/else. – someone Dec 02 '17 at 13:20
  • 1
    I think a simple `if`/`else` statement should the trick. I wouldn't say there was anything unclean about it. In addition to my previous suggestion, I would probably define an `updateDefinition` variable outside of the `if`/`else`, and then declare it with the statement. Then, you only need to have on line which updates the collection, using whatever the `updateDefinition` was defined as. – Geoff James Dec 02 '17 at 14:40

0 Answers0