Find by embeded object field value

Hello, can enyone help me how to use MongoTemplate to find documents by embeded object value?

I have a classes:

@Document("items")
public class GroceryItem {
    @Id
    private String id;

    private String name;
    private Integer quantity;
    private String category;

    private List<Product> products;
...

Embeded class:

public class Product {
    private String name;
    private List<Level> levels;
 ...

and

public class Level {
    private String name;
...

How can I find document by embeded product “name” or level “name” field?

It is not working with query:

Query query = new Query(Criteria.where("name").is(name)
                .and("products.name").is(productName));

With @Query annotation it works fine:

@Query(value = "{ 'quantity' : ?0, 'products.name' : ?1, 'products.levels.name' : ?2 }")
Stream<GroceryItem> findByQuantityProdNameLevelName(int quantity, String prodName, String level);

Thanks.

Solution found with MongoClient and Filters class approach:

CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));

        MongoCollection<GroceryItem> collection = MongoClients.create(dbConnString)
                .getDatabase("gettingstarted").withCodecRegistry(pojoCodecRegistry)
                .getCollection("groceryitems", GroceryItem.class);

        FindIterable<GroceryItem> items = collection.find(eq("products.levels.name", "level1"), GroceryItem.class);

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.