1

I have a mongo document like below

{
    "_id" : ObjectId("588adde40fcbbbc341b34e1c"),
    "title" : "Fifa world cup",
    "tags" : [ 
        {
            "name" : "Football",
            "type" : "Sports"
        }, 
        {
            "name" : "World cup",
            "type" : "Sports"
        }, 
        {
            "name" : "Fifa",
            "type" : "Manager"
        }
    ]
}

I wrote the below query to get all the tags with type Sports but I am only getting 1 item instead of 2

db.collection.find(
{ 
    tags: 
    { 
        $elemMatch: 
        { 
                type: "Sports" 
        }
    }
},
{
    "tags.$" : 1
})

Is it possible to get all the matching items? What I am missing here?

Janis
  • 8,593
  • 1
  • 21
  • 27
ehp
  • 2,495
  • 6
  • 29
  • 43

1 Answers1

2

You can use aggregation:

db.collection.aggregate([
{
    $unwind : "$tags"
},
{
    $match : {
        "tags.type" : "Sports"
    }
},
{
    $group : {
        _id : "$_id",
        tags : {$addToSet : "$tags"}
    }
}
])
ares
  • 4,283
  • 6
  • 32
  • 63
  • hmm, I could use aggregate but i am actually looking for something simple. Though i am not sure if there are other way to do it. Thank you. – ehp Jan 28 '17 at 08:07
  • `$elemMatch` projection [returns only the first matching element](https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#zipcode-search), so you will have to use aggregation. – ares Jan 28 '17 at 08:20