1

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:

  • x = 4 the document should not be found (3 matching values but x is 4)
  • x = 3 document should be found (3 matching -> size = x)
  • x = 2 the document should not be found (3 matching values but x is 2)
  • x = 1 the document should not be found (3 matching values but x is 1)
2
  • Not really that clear. Are you looking for all documents that contain a sub-set of your required array or those that match all of it? Otherwise what exactly are you asking? Commented Jun 4, 2014 at 7:25
  • Excuse me if its not clear. I was asking for a sub-set of a fixed length. See the excepted answer. Commented Jun 4, 2014 at 15:50

1 Answer 1

1

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 } }
]);
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.