ferensilver
ferensilver

Reputation: 351

MongoDB updateOne

I am trying to update an existing Mongo record, but am getting an "Additional information: Element name 'ID' is not valid'." error

I have a a BsonDocument "document" containing data that I retrieve from another source that looks like this:

{ "ID" : "ABCecdcf9851efbf0ef66953", ListingKey : "234534345345", "Created" : ISODate("2017-08-04T00:31:23.357Z"), "Modified" : ISODate("2017-08-04T00:31:23.358Z"), "Field1" : 1, "Field2" : "0.09", "Field3" : "1.10", "Field4" : "1", "Field5" : "1" }

Here is the C# code that I have written:

var collection = db.GetCollection<BsonDocument>("MyCollection");                              

//Hard coded for testing
var filter = Builders<BsonDocument>.Filter.Eq("ListingKey", "234534345345");

collection.UpdateOne(filter, document);

Is this related to the BsonDocument that I am trying to use to update? I found this documentation, which causes me to think that this is the cause. If so, is there a way to do an update with the format I have been provided?

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

I had a process working where it would delete the document and then add a new document, but for efficiency's sake I need this to update. Ideally it will only update the fields that are present in the BsonDocument and keep the existing fields in the Mongo document as is.

Upvotes: 6

Views: 26364

Answers (1)

ferensilver
ferensilver

Reputation: 351

My problem was because I did not have the correct value when trying to update. My code works with this:

var collection = db.GetCollection<BsonDocument>("MyCollection");                              

//Hard coded for testing
var filter = Builders<BsonDocument>.Filter.Eq("ListingKey", "234534345345");

var update = Builders<BsonDocument>.Update.Set("Created", DateTime.UtcNow);
foreach (BsonElement item in document)
{
    update = update.Set(item.Name, item.Value);
}
var result = collection.UpdateOne(filter, update);

I had to convert my string into an update BsonDocument.

Upvotes: 11

Related Questions