What is the equivalent to this mongo shell query in mongoTemplate?

Following is my collection:

[
  {
    "_id": 1,
    "favorite": {
      "color": "red",
      "foods": {
        "fruits": "banana",
        "fastfood": [
          "burger",
          "sandwich"
        ]
      }
    }
  },
  {
    "_id": 2,
    "favorite": {
      "color": "green",
      "foods": {
        "noodles": "ramen",
        "fastfood": [
          "fries",
          "burger",
          "corn dog"
        ]
      }
    }
  },
  {
    "_id": 3,
    "favorite": {
      "color": "red",
      "foods": {
        "soup": "cream soup"
      }
    }
  }
]

I am getting the desired result using the following mongo shell query:

db.collection.find({
  $expr: {
    $eq: [
      [
        "burger",
        "sandwich"
      ],
      "$favorite.foods.fastfood"
    ]
  }
})

But, I need this same result in mongoTemplate. I am unable to do that.

Hi @Abhijit_Mondal_Abhi and welcome to MongoDB community forums!!

Based on the sample data and the query provided, you can use the code given below using mongoTemplate:

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Arrays;
import java.util.List;

import org.bson.Document;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @Bean
    public CommandLineRunner demo(MongoTemplate mongoTemplate) {
        return (args) -> {
            Query query = new Query(Criteria.where("favorite.foods.fastfood").in(Arrays.asList("burger", "sandwich")));
            List<Document> result = mongoTemplate.find(query, Document.class, "post240337");

            for (Document document : result) {
                System.out.println(document);
            }
        };
    }
}

Output:

Document{{_id=1, favorite=Document{{color=red, foods=Document{{fruits=banana, fastfood=[burger, sandwich]}}}}}}
Document{{_id=2, favorite=Document{{color=green, foods=Document{{noodles=ramen, fastfood=[fries, burger, corn dog]}}}}}}

Place your configuration for the connection url in the application.properties file.

Reach out in case of any further questions.

Warm Regards
Aasawari