2

I have simple question:

How do I express this query

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

Query for a Document Nested in an Array

in spring data mongoDB, preferably using QueryDSL but other ways are welcome, too.

All my queries so far match fields on any embedded document in the array but I need to match both on the same.

1 Answer 1

8

Using Spring Data repository, you could use :

1 - @Query annotation

@Query("{ 'instock': { 'warehouse': ?0, 'qty': ?1 } }")
List<YourClass> findByInstock(String warehouse, int qty);

2 - Custom repository method implementation

List<YourClass> findByInstock(String warehouse, int qty) {
  return mongoTemplate.find(Query.query(Criteria.where("instock").elemMatch(Criteria.where("warehouse").is(warehouse).and("qty").is(qty)));

You can find more material here on how to implement this method. }

Sign up to request clarification or add additional context in comments.

2 Comments

@user3813234 , did you manage to setup the query or do you need more material?
Hi, I used your second apprach with the elemMatch. Worked perfectly! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.