Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo throwing "Element name 'name' is not valid' exception

I'm updating a simple field.

var filterDocument = new BsonDocument { { "name", "alice" } };

var newDocument = new BsonDocument { { "name", "Alice" } };

collection.UpdateOne(filterDocument, newDocument);

But when I reach the the update statement I get an exception {"Element name 'name' is not valid'."}

What's wrong with that element name?

Update

Re-writing it to this:

var filterDocument = new BsonDocument { { "x", "alice" } };

var newDocument = new BsonDocument { { "y", "Alice" } };

collection.UpdateOne(filterDocument, newDocument);

Throw the exception {"Element name 'y' is not valid'."}

Also, UpdateOne() or UpdateMany() makes no difference.

Also, from the shell it's fine.

> db.crud.update({name:'alice'},{name:'Alice'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
like image 686
BanksySan Avatar asked Feb 16 '16 18:02

BanksySan


1 Answers

In contrast to update, updateOne seems to require an update operator;

> db.test.updateOne({name:'alice'},{name:'Alice'})
2016-02-16T19:04:07.689+0000 E QUERY    [thread1] Error: the update operation document must contain atomic operators

> db.test.updateOne({name:'alice'},{$set: {name:'Alice'}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

...which means your document should probably look like;

var newDocument = 
    new BsonDocument { { "$set", new BsonDocument {"name", "Alice" } } };

...or if you really mean to replace the entire document, use replaceOne, which should work with your existing documents to replace the entire matching document.

like image 132
Joachim Isaksson Avatar answered Oct 21 '22 13:10

Joachim Isaksson