Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

aggregation framework - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...