0
votes

In this MSDN sample, when I ran it the 2nd time w/ different values for "author" and "title"

using (mongo.RequestStart(db)) 
{ 
    var collection = db.GetCollection<BsonDocument>("books"); 

    BsonDocument = new BsonDocument() 
        .Add("_id", BsonValue.Create(BsonType.ObjectId)) 
        .Add("author", "Ernest Hemingway") 
        .Add("title", "For Whom The Bell Tolls"); 

        collection.Insert(book); 
}

I got this error: Additional information: WriteConcern detected an error ''. (Response was { "err" : "E11000 duplicate key error index: test.test.$id dup key: { : 7 }", "code" : 11000, "n" : 0, "connectionId" : 4, "ok" : 1.0 }).

Basically, "_id" is getting value 7 again. I thought BsonValue.Create(BsonType.ObjectId) is supposed to create a unique 24 character hex string.

1

1 Answers

2
votes

Two different things here. To create an new ObjectId then use:

 var id = ObjectId.GenerateNewId();

What you have is the constant value for the enumeration of the "BSON Type", which for an "ObjectId" that constant number is 7.

So "create" an ObjectId. All you are doing right now is calling the constant value for the type.