Spring Data: Update an element in an objects array of a nested MongoDB document

Viewed 83

I'm building Spring/MongoDB backend app for an online store and I have the next structure of MongoDB document:

'client_data': [
  '_id': 'sdas2DSA',
  'client_name': 'aurelis',
  'stores': [
    {
      'store_id': 1,
      'products': [
        {
          'product_id': 1,
          'name': 'T-shirt',
          'price': 120
        },
        {
          'product_id': 2,
          'name': 'Pants',
          'price': 120
        },
      ],
    }
  ]
]
strong text

I need to implement logic of updating a product entity of the given client's store by product_id, but I'm stucked at the stage of querying.

Suppose the client with the 'client_name'='aurelis' is sent a post request with parameter 'store_id'=1 with the given body:

{
  'product_id': 1,
  'name': 'T-shirt',
  'price': 90
},

How can I built an query that updates the product object of the specific client's store by product_id?

I tried to implement the functionality by myself:

    Query query = new Query(new Criteria().andOperator(
    Criteria.where("client_name").is(clientName),
    Criteria.where("stores.store_id").is(storeId),Criteria.where("stores.products").elemMatch(Criteria.where("products.product_id").is(product_id))
));
Update update = new Update().set("stores.products", product)
mongoTemplate = new MongoTemplate().findAndModify(query, update, Product.class);

but it doesn't work.

I'd be grateful for your answers:)

0 Answers
Related