Amazia Gur
Amazia Gur

Reputation: 1722

get number of elements from embedded array as a response mongoDB

Please see the following document:

{
    "assetId": ObjectId("5214817cccf3d82198561444"),
    "entityType": "MOVIE",
    "lastUpdate": NumberLong(1392034838964),
    "name": "testMovie",
    "resources": [
        {
            "jobId": ObjectId("52f8c302056f0728d16951f6"),
            "lastModifiedTime": NumberLong(1392034563729),
            "name": "testMovie",
            "status": "ERROR",
            "type": "IMAGE_3_2"
        },
        {
            "jobId": ObjectId("52f8c416056f0728d16951fd"),
            "lastModifiedTime": NumberLong(1392034838964),
            "name": "testMovie",
            "status": "ERROR",
            "type": "IMAGE_3_1"
        }
    ],
    "sandBoxId": "52146e1bccf26997695ca9c0",
    "sandboxName": "test"
}

I'm trying to figure out how to write a query which will respond me number of elements from "resources" array by "type".

for example (ill write it in pseudocode and not a mongo query): match assetId:5214817cccf3d82198561444 where resource.type=IMAGE_3_1&IMAGE_3_2

the response in this case should be :

 {
                "jobId": ObjectId("52f8c302056f0728d16951f6"),
                "lastModifiedTime": NumberLong(1392034563729),
                "name": "testMovie",
                "status": "ERROR",
                "type": "IMAGE_3_2"
            },
            {
                "jobId": ObjectId("52f8c416056f0728d16951fd"),
                "lastModifiedTime": NumberLong(1392034838964),
                "name": "testMovie",
                "status": "ERROR",
                "type": "IMAGE_3_1"
            }

i figured out how to get a single element from the array as a response, but not number of elements.

*Again, sorry for the pseudocode

Upvotes: 2

Views: 88

Answers (2)

Rishi
Rishi

Reputation: 268

If you are looking for only a count, then:

    db.collection.aggreate([
        {$unwind: "$resources"},
        {$match: {"assetId": ObjectId("5214817cccf3d82198561444"), "resources.type": {$in: ["IMAGE_3_1", "IMAGE_3_2"]}}}
        {$group: { _id: null, count: { $sum: 1 }}
    ])

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151170

To get multiple results from inside an array, use aggregate and $unwind.

db.collection.aggregate([
    {$unwind: "$resources"},
    {$match: { "resources.type": {$in :["IMAGE_3_1", "IMAGE_3_2"]}} },
    {$project: {_id: 0, resources: 1} }
])

Optionally $match first as well to limit the documents being processed in aggregation to only those that will contain a match. The $project phase can be whatever your result needs.

Upvotes: 1

Related Questions