3

Having, for example, a collection named test and the following document is inside:

{
    "_id" : ObjectId("5692ac4562c824cc5167379f"),
    "list" : [ 
        {
            "name" : "elem1",
            "type" : 1
        }, 
        {
            "name" : "elem2",
            "type" : 2
        }, 
        {
            "name" : "elem3",
            "type" : 1
        }, 
        {
            "name" : "elem4",
            "type" : 3
        }, 
        {
            "name" : "elem4",
            "type" : 2
        }
    ]
}

Let's say I would like to retrieve a list of only those subdocuments inside list that match:

  • type = 2.

I've tried the following query:

db.getCollection('test').find({
    '_id': ObjectId("5692ac4562c824cc5167379f"),
    'list.type': 1
})

But the result I get contains every subdocument inside list, and I guess this is because inside list there are at least one document which's type equals 1.

Instead of that, the result I am interested to obtain would be every subdocument inside list that matches 'list.type': 1:

{
    "_id" : ObjectId("5692ac4562c824cc5167379f"),
    "list" : [ 
        {
            "name" : "elem1",
            "type" : 1
        }, 
        {
            "name" : "elem3",
            "type" : 1
        }
    ]
}

...so $and $elemMatch is not what I am really looking for as they return just the first matching element.

Anyone knows how to achieve what I am looking for?

charliebrownie
  • 4,591
  • 8
  • 28
  • 49
  • 1
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Jan 10 '16 at 20:09
  • 1
    @user3100115 NOT REALLY, I don't want ONLY ONE element, I want ALL THE MATCHING elements!!! – charliebrownie Jan 10 '16 at 20:19
  • 4
    Check the answers that used the `.aggregate()` method. – styvane Jan 10 '16 at 20:21

1 Answers1

0
db.myCol.aggregate([ 
                    { $unwind: "$list" }, 
                    { $match: { "list.type":1 } }, 
                    { $group: { "_id":"$_id", list: {$push:"$list"}} }
])
yoooshi
  • 2,788
  • 4
  • 13
  • 13