David Rojo
David Rojo

Reputation: 2394

Return union of embedded arrays

I have a collection with documents, each document has an array. I want to get an array which is the result of the union of the document's embedded arrays.

This is my collection:

{
    "_id": ObjectId("...."),
    "filter": "a",
    "images": [
        {
            "_id": ObjectId("...."),
            "file": "file_a_1.jpg"
        },
        {
            "_id": ObjectId("...."),
            "file": "file_a_2.jpg"
        }
    ]
},
{
    "_id": ObjectId("...."),
    "filter": "b",
    "images": [
        {
            "_id": ObjectId("...."),
            "file": "file_b_3.jpg"
        },
        {
            "_id": ObjectId("...."),
            "file": "file_b_4.jpg"
        }
    ]
},
{
    "_id": ObjectId("...."),
    "filter": "a",
    "images": [
        {
            "_id": ObjectId("...."),
            "file": "file_a_5.jpg"
        },
        {
            "_id": ObjectId("...."),
            "file": "file_a_6.jpg"
        }
    ]
}

And I would like to get the embedded arrays of the documents with filter = "a" for example.

{
    "_id": ObjectId("...."),
    "file": "file_a_1.jpg"
},
{
    "_id": ObjectId("...."),
    "file": "file_a_2.jpg"
},
{
    "_id": ObjectId("...."),
    "file": "file_a_5.jpg"
},
{
    "_id": ObjectId("...."),
    "file": "file_a_6.jpg"
}

And I would like to be able to limit the size of the returned array and the offset.

Upvotes: 3

Views: 161

Answers (1)

profesor79
profesor79

Reputation: 9473

you need to unwind such array, then project to get new document shape.

db.david1.aggregate([{
            $match : {
                "filter" : "a"
            }
        }, {
            $unwind : "$images"
        }, {
            $project : {
                _id : "$images._id",
                file : "$images.file"
            }
        }, {
            $skip : 2
        }, {
            $limit : 1
        }
    ]).toArray()

Upvotes: 1

Related Questions