作为响应mongoDB从嵌入式数组获取元素数
请参阅以下文件:作为响应mongoDB从嵌入式数组获取元素数,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,请参阅以下文件: { "assetId": ObjectId("5214817cccf3d82198561444"), "entityType": "MOVIE", "lastUpdate": NumberLong(1392034838964), "name": "testMovie", "resources": [ { "jobId": ObjectId("52f8c302056f0728d16951f6"),
{
"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"
}
我试图弄清楚如何编写一个查询,该查询将按“类型”响应“resources”数组中的元素数
例如(我将用伪代码编写,而不是mongo查询):
匹配assetId:5214817cccf3d82198561444,其中resource.type=IMAGE\u 3\u 1和IMAGE\u 3\u 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"
}
我知道如何从数组中获取单个元素作为响应,而不是元素数
*同样,对于伪代码很抱歉,要从一个数组中获得多个结果,请使用aggregate和
也可以选择$match first,将聚合处理的文档限制为仅包含匹配项的文档。$project阶段可以是您的结果所需的任何阶段。如果您只寻找一个计数,那么:
db.collection.aggreate([
{$unwind: "$resources"},
{$match: {"assetId": ObjectId("5214817cccf3d82198561444"), "resources.type": {$in: ["IMAGE_3_1", "IMAGE_3_2"]}}}
{$group: { _id: null, count: { $sum: 1 }}
])
db.collection.aggreate([
{$unwind: "$resources"},
{$match: {"assetId": ObjectId("5214817cccf3d82198561444"), "resources.type": {$in: ["IMAGE_3_1", "IMAGE_3_2"]}}}
{$group: { _id: null, count: { $sum: 1 }}
])