coding2
coding2

Reputation: 57

Query an array based on multiple conditions

I have this Array

    "food": [
    {
        "id": "2023",
        "type": "mexican",
    },
    {
        "id": "2023",
        "type": "italian",
    },
     {
        "id": "2024",
        "type": "chinese",
    }]

I created this Query:

@Query(value = "{$and: [{'dependencies.id' : ?0}, {'dependencies.type': ?1}]}",
Optional<Food> findByIdAndType(String id, String type);

If I give these values:

id = 2023, type = mexican

I am getting this result:

    "food": [
    {
        "id": "2023",
        "type": "mexican",
    },
    {
        "id": "2023",
        "type": "italian",
    }]

Is not working properly because I want to have just the elements within the array food, where the id and the type are equal to the input. For the example, I am expecting to have:

    "food": [
    {
        "id": "2023",
        "type": "mexican",
    }]

I do not know how can I query each element of my array

Upvotes: 1

Views: 435

Answers (1)

Ramit Mittal
Ramit Mittal

Reputation: 573

The $and operator will return true if there is at least one element in array where id = 2023 and type = mexican. But these do not need to be the same element. To find one element that matches both conditions, use $elemMatch.

{
  "food": {
    "$elemMatch": {
      "id": 0,
      "type": "mexican"
    }
  }
}

The returning document will contain the entire array, not just the matched element. To return only the required item from the array use $ operator in projection.

{
  "food.$": 1
}

Upvotes: 0

Related Questions