从嵌入式数组中获取元素数作为响应mongoDB

时间:2014-02-10 20:16:52

标签: mongodb mongodb-query aggregation-framework

请参阅以下文件:

{
    "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"
}

我正在试图弄清楚如何编写一个查询,它将通过“type”响应“resources”数组中的元素数量。

例如

(用伪代码编写,而不是mongo查询): match assetId:5214817cccf3d82198561444其中resource.type = IMAGE_3_1& IMAGE_3_2

这种情况下的回答应该是:

 {
                "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"
            }

我想出了如何从阵列中获取单个元素作为响应,但不是元素数量。

*再次,抱歉伪代码

2 个答案:

答案 0 :(得分:1)

要从数组中获取多个结果,请使用aggregate和$unwind

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

可选择首先匹配$以将聚合中处理的文档限制为仅包含匹配项的文档。 $ project阶段可以是您需要的任何结果。

答案 1 :(得分:0)

如果您只想要一个计数,那么:

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