Search code examples
javamongodbbson

Mongo function updatemany() is not working when Bson filters are passed


Below is the data present in Mongo DB

{"name":"john","id":"123","location":"Pune"}
{"name":"steve","id":"456","location":"Noida"}

I want to upsert the "id" to "789" and "name" to "alex" where "name":"john" and "location":"Pune" and as per upsert funtionality, if the query condition is not present, then it needs to create a new entry.

I am using the below logic to do this using Bson filter, but i am getting the below exception

Bson filter=null;
Bson update=null;

filter=combine(eq("name":"john"),eq("location":"Pune"));
update=combine(eq("id":"123"),eq("name":"alex"));
UpdateOptions options = new UpdateOptions();
options.upsert(true);
dbCollection.updateMany(filter, update,options);

I am expecting below change in my Mongo DB data :

{"name":"alex","id":"789","location":"Pune"}

But I'm getting below Exception :

Exception is java.lang.IllegalArgumentException: Invalid BSON field name portalID
java.lang.IllegalArgumentException: Invalid BSON field name portalID
at org.bson.AbstractBsonWriter.writeName(AbstractBsonWriter.java:532)

Can some one suggest me?


Solution

  • Try the following code:

    Bson filter = null;
    Bson update = null;
    
    filter = and(eq("name", "john"), eq("location", "Pune"));
    update = combine(set("id", "789"), set("name", "alex"));
    UpdateOptions options = new UpdateOptions();
    options.upsert(true);
    dbCollection.updateMany(filter, update, options);