Aggregation pipeline - check if array contains values in $switch

Hello,

I’m building an Android app. In the aggregation pipeline, I added an “order” field with a value dependent on 3 conditions. The part I can’t figure out is querying array - 2nd and 3rd condition which you can see below.

  1. When field $mainInterest(string) == “potato” then order = 1 - This part is working fine for me with the code below, so don’t worry about this
  2. When field $otherInterests(array) contains “potato” then order = 2 - This is not working
  3. When field $otherInterests(array) contains any element from array [“potato”, “hiking”, “traveling”] then order = 3 - this is also not working for me.

Below you can see my code:

List<Document> pipeline =
        Arrays.asList(
                new Document("$addFields", new Document("order", new Document("$switch", new Document("branches", Arrays.asList(
                        new Document("case", new Document("$eq", Arrays.asList("$mainInterest", "potato"))).append("then", 1),
                        new Document("case", new Document("$eq", Arrays.asList("$otherInterests", "potato"))).append("then", 2),
                        new Document("case", new Document("$in", Arrays.asList("$otherInterests", Arrays.asList("potato", "hiking", "traveling")))).append("then", 3)
                )).append("default", 4))))
        );

The first condition is working, so I suppose syntax is correct, I’m trying to figure it out for a few days and I have no idea what could be wrong here, so if someone could help me, I would be greatful :slight_smile:

To find a single element in an array you can use $in or $indexOfArray or you can do it the same way as finding one of several elements, use one of set expressions, like $setIsSubset

Asya

1 Like

I already found a solution, thank you for your answer :slight_smile: