Search code examples
javamongodbfilterdriverbulk

How to perform a bulk update of documents with multiple filters in MongoDB 3 with Java


I want to make a Bulk Update like this:

        List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(
            new UpdateOneModel<Document>(
                    new Document("car", "Ferrari"), // filter
                    new Document("$set", new Document("color", "Black")) // update
            )
    );

But I want to input more than one filter. I thought it would be something like this:

        List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(
            new UpdateOneModel<Document>(
                    new Document(and(eq("car", "Ferrari"), eq("color", "Red"), // filter
                    new Document("$set", new Document("color", "Black")) // update
            )
    );

But it obviously doesn't work, and I can't find it anywhere. Does anyone know if there is any way to do it? Thank you :)


Solution

  • Use append to add the other keys:

    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(
        new UpdateOneModel<Document>(
            new Document("car", "Ferrari").append("color", "Red"), // filter
            new Document("$set", new Document("color", "Black")) // update
        )
    );