earandap
earandap

Reputation: 1496

Passing array as parameter in filter function with spring-data-mongodb

I have this collection of documents:

[
    {
        "name": "name1",
        "data": [
            {
                "numbers": ["1","2","3"]
            }
        ]
    },
    {
        "name": "name2",
        "data": [
            {
                "numbers": ["2","5","3"]
            }
        ]
    },
    {
        "name": "name3",
        "data": [
            {
                "numbers": ["1","5","2"]
            }
        ]
    },
    {
        "name": "name4",
        "data": [
            {
                "numbers": ["1","4","3"]
            }
        ]
    },
    {
        "name": "name5",
        "data": [
            {
                "numbers": ["1","2"]
            }
        ]
    }
]

I want to get all documents of this collection when an array passed as a parameter is a subset of data.numbers.

This is the aggregation that I'm using.

db.testing.aggregate(
    [
        { "$match" : { "data.numbers" : { "$exists" : true } } }, 
        { "$project" : { "is_subset" : { "$filter" : { "input" : "$data", "as" : "d", "cond" : { "$setIsSubset" :[ ["1"],"$$d.numbers"] } } } } }, 
        { "$match" : { "is_subset.0" : { "$exists" : true } } }]
);

I'm trying to reproduce the above aggregation in Spring Data MongoDB.

How to pass an array as parameter in $filter and $setIsSubset functions?

 operations.aggregate(
                    newAggregation(Testing.class,
                            match(where("data.numbers").exists(true)),
                            project().and(
                                    filter("data")
                                            .as("d")
                                            .by(???))
                                    .as("is_subset"),
                            match(where("is_subset.0").exists(true))
                    ), Testing.class);

Upvotes: 2

Views: 1270

Answers (1)

earandap
earandap

Reputation: 1496

I solve my issue.

operations.aggregate(
                newAggregation(Testing.class,
                        match(where("data.numbers").exists(true)),
                        project("id", "name").and(
                                filter("data")
                                        .as("d")
                                        .by(context -> new Document("$setIsSubset", Arrays.asList(numbers, "$$d.numbers"))))
                                .as("is_subset"),
                        match(where("is_subset.0").exists(true))
                ), Testing.class);

I created a Document with the content that I needed in the $filter condition.

new Document("$setIsSubset", Arrays.asList(numbers, "$$d.numbers"))

Upvotes: 2

Related Questions