Marco
Marco

Reputation: 656

Get array subset in mongodb using an array source

I have this document's structure:

{
    Id: "id_value",
    Elements:[
                {
                    InnerId: "inner_id_value1",
                    Value: "apple"
                },
                {
                    InnerId: "inner_id_value2",
                    Value: "pear"
                },
                {
                    InnerId: "inner_id_value3",
                    Value: "banana"
                }
             ]
}

What i need to do is create a query which receives in input an array (for example ["apple","banana","coconut"] ) and returns to me:

{
    Id: "id_value",
    Elements:[
                {
                    InnerId: "inner_id_value1",
                    Value: "apple"
                },
                {
                    InnerId: "inner_id_value3",
                    Value: "banana"
                }
             ]
}

Is it possible do it in Mongo with a single query?

Upvotes: 4

Views: 589

Answers (1)

Sede
Sede

Reputation: 61235

You simply need to $filter the array and keep only those subdocument where the value is a subset of your input array. Note that value here is one element array where element is the embedded field value.

let fruits = ["apple","banana","coconut"];

db.collection.aggregate([
    { "$project": { 
        "Element": { 
            "$filter": { 
                "input": "$Element", 
                "as": "el", 
                "cond": { 
                    "$setIsSubset": [ [ "$$el.Value" ], fruits ] 
                 }
            }
        }
    }}
])

Starting from MongoDB 3.4* you can use the $in operator in the $project stage.

db.collection.aggregate([
    { "$project": { 
        "Element": { 
            "$filter": { 
                "input": "$Element", 
                "as": "el", 
                "cond": { 
                    "$in": [ "$$el.Value", fruits ] 
                 }
            }
        }
    }}
])

*Unreleased version of MongoDB as the time of this writing

Upvotes: 4

Related Questions