Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-1805

Collection.ReplaceOne() with upsert flag does not auto-generate Id

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 2.3
    • Component/s: API
    • None
    • Environment:
      windows10, .net46, .netCore
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      Given an entity defined as such:

      public class Foo
      {
      public ObjectId Id

      { get; set; }
      public string Bar { get; set; }

      }

      I want the ability to "upsert" a document with an object having that type, where a new record would have an auto-generated "_id". After executing the following:

      var foo = new Foo

      { Bar = "hello world" }

      ;
      collection.ReplaceOne(x => x.Id.Equals(foo.Id), foo, new UpdateOptions

      { IsUpsert = true }

      );

      The mongo shell, however, reports the following:
      > db.foo.find()

      { "_id" : ObjectId("000000000000000000000000"), "Bar" : "hello world" }

      The _id inserted is equivalent to ObjectId.Empty. Even applying the [BsonIgnoreIfDefault] attribute atop the Id property has no effect.

      Expected Behavior:

      The .ReplaceOne() and .ReplaceOneAsync() methods would recognize that the Id has not been explicitly initialized and will "insert" with an auto-generated _id (when used in conjunction with the "upsert" flag) instead of performing, what it appears to be, an "update".

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            tbehunin Todd Behunin
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: