SeeM
SeeM

Reputation: 43

Mongo find documents where array contains x values of given array

I have a collection which has documents like that one. The entity field is not set in each document and has different values:

{
    "_id" : ObjectId("5388cfbdec82ba7cd5438635"),
    "name" : "Name1",
    "entity" : [ 
        "Entity1", 
        "Entity2", 
        "Entity4",
        "Entity5"
    ]
}

Now I want to find all documents which contains exactly x values of the given array : ["Entity1","Entity2","Entity3","Entity4"]

Expected result

For the document posted above the values Entity1, Entity2, Entity4 are matching:

Upvotes: 1

Views: 405

Answers (1)

Christian P
Christian P

Reputation: 12240

You can use .aggregate for this. This is probably what you're looking for:

var y = ["Entity1", "Entity2", "Entity3", "Entity4"];
db.col.aggregate([
    {
        $project :
        {
            _id : 1,
            name : 1,
            entity : 1,
            x : {
                $size : {
                    $ifNull: [{$setIntersection : ["$entity", y]}, []]
                }
            }
        } 
    },
    { $match : { x : 3 } }
]);

Upvotes: 1

Related Questions