skip to Main Content
UpdateOptions options = new UpdateOptions().upsert(true);

Bson filters = Filters.eq("id", 123456);

List<Bson> bsonArrayList = new ArrayList<>();
bsonArrayList.add(Updates.set("income", "$300k"));

UpdateResult updateResult = mongoExe.updateOne(filters, bsonArrayList, options);

The field name is income, value is $200k. It can’t update until I delete the $

bsonArrayList.add(Updates.set("income", "300k"));

how can I do to make it ?

why java mongodb driver update a value can’t start with $?

2

Answers


  1. The $ is a special character in MongoDB, see here for a description.

    You can fix it by escaping the character, see here for how.

    Login or Signup to reply.
  2. You can use literal:

    import static com.mongodb.client.model.Filters.eq;
    
    ...
    bsonArrayList.add(Updates.set("income", eq("$literal", "$300k")));
    

    or

    bsonArrayList.add(Updates.set("income", new Document("$literal", "$300k")));
    
    

    eq is just a container (or shorthand for Document) in this case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search