2

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);

1 Answer 1

2

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"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.