0

I am using Spring boot 2.2.1.RELEASE. How can I write the below MongoDB update query with Spring MongoOperation

db.cities.updateOne(
  {
    _id : ObjectId("5e78ec62bb5b406776e92fac")
  },
  { 
    $inc: { 
      "subscriptions.$[category].subscribers" : 1,
      "subscriptions.$[category].options.$[option].subscribers" : 1
    }
  },
  { multi: true,
    arrayFilters: [
      { "category._id": {$in: ["1", "2"]} },
      { "option.name": {$in: ["Time", "Gourmand", "Politics", "Entrepreneurship"]} } 
    ]
  }
)

I have tried the following

Update update = new Update().inc("subscriptions.$[category].subscribers", 1).inc("subscriptions.$[category].options.$[option].subscribers", 1).filterArray(Criteria.where("category._id").in(Arrays.asList("1", "2")).andOperator(Criteria.where("option.name").in(Arrays.asList("Time", "Gourmand", "Politics", "Entrepreneurship"))));
UpdateResult result = mongoOperations.updateFirst(new Query(where("id").is(cityId)), update, CitiesDoc.class);

But I keep getting the following error

org.springframework.dao.InvalidDataAccessApiUsageException: Command failed with error 9 (FailedToParse): 'Unrecognized field in update operation: arrayFilters' on server localhost:56740. The full response is {"ok": 0.0, "errmsg": "Unrecognized field in update operation: arrayFilters", "code": 9, "codeName": "FailedToParse"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 9 (FailedToParse): 'Unrecognized field in update operation: arrayFilters' on server localhost:56740. The full response is {"ok": 0.0, "errmsg": "Unrecognized field in update operation: arrayFilters", "code": 9, "codeName": "FailedToParse"}

Not sure for which field it is giving the error. Some suggestion will be helpful.

Meena Chaudhary
  • 9,909
  • 16
  • 60
  • 94

2 Answers2

1

It worked with the following query

update = update.inc("subscriptions.$[category].subscribers", 1);
update = update.inc("subscriptions.$[category].options.$[option].subscribers", 1);
update = update.filterArray(Criteria.where("category._id").in(Arrays.asList("1", "2")));
update = update.filterArray(Criteria.where("option.name").in(Arrays.asList("Time", "Gourmand", "Politics", "Entrepreneurship")));

UpdateResult result = mongoOperations.updateFirst(new Query(where("id").is(cityId)), update, CitiesDoc.class);

But the cause for the error was MongoDB version. I am using flabdoodle as embedded MongoDB for testing. And the default MongoDB version is 3.5.5. Which I believe don not support arrayFilters. Updating the version to 4.x resolved the issue. You can look into this answer on how to update the version to latest supported production version.

Meena Chaudhary
  • 9,909
  • 16
  • 60
  • 94
1

Add the following to application.yaml:

spring:
  mongodb:
    embedded:
      version: 4.0.2
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Oleg
  • 11
  • 2