Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid BSON field name [duplicate]

Tags:

java

json

mongodb

I looked up similar answers to this question but unable to find any.

public void update(String id, String user) {
    Document document = Document.parse(user);
    UpdateResult result = database.getCollection("user")
            .updateOne(Filters.eq("_id", new ObjectId(id)), document);

    System.out.println(result);
}

My JSON payload looks like this.

{
    "first": "John",
    "last": "Doe",
    "email": "[email protected]",
}

Error

Invalid BSON field name first

if I remove first from the payload, it objects on the last and so on.

like image 935
AppDeveloper Avatar asked Mar 13 '26 02:03

AppDeveloper


1 Answers

updateOne(Filters.eq("_id", new ObjectId(id)), document);
This is caused by your document format
updateOne({here is condition }, {here is operation})

The document does't have any operation in it ,so it caused this error. You should put it like this:

database.getCollection("user")
        .updateOne(Filters.eq("_id", new ObjectId(id)), combine(set( <field1>, <value1>), set(<field2>, <value2> ) ));

Here is the official document

In your case, you can try to use replaceOne() with your code like

collection.replaceOne(eq("item", "paper"),
       Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
like image 113
HbnKing Avatar answered Mar 15 '26 15:03

HbnKing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!