4

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?

2
  • What is your MongoDB version? Commented Sep 29, 2016 at 15:35
  • @Styvane version 3.2 Commented Sep 29, 2016 at 15:36

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

$setIsSubset is new to me. Thanks! Just curious about the null set scenario, since it is a subset of every set - if $$el.Value is empty for a document, wont that also be included in this query result?
No it will not be included.

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.