寻找嵌套的数组mongodb

所以我有一个这样的MongoDB文件:

[ { "_id": "04", "name": "test service 4", "id": "04", "version": "0.0.1", "title": "testing", "description": "test", "protocol": "test", "operations": [ { "_id": "99", "oName": "test op 52222222222", "sid": "04", "name": "test op 52222222222", "oid": "99", "description": "testing", "returntype": "test", "parameters": [ { "oName": "Param1", "name": "Param1", "pid": "011", "type": "582", "description": "testing", "value": "" }, { "oName": "Param2", "name": "Param2", "pid": "012", "type": "58222", "description": "testing", "value": "" } ] } ] } ] 

我想能够find所有的参数和个人,但我不完全确定,如果我使用这个:

  collection.find({operations: {$elemMatch: {oid: oid}}}, {"operations.$.parameters": 1}).toArray(function(error, result) { if (error) { console.log('Error retrieving parameter: ' + error); res.send({'error':'An error has occurred'}); } else { // console.log(result); res.send(result); } }); 

我得到的输出是这样的:

 [ { "_id": "04", "operations": [ { "_id": "99", "oName": "test op 52222222222", "sid": "04", "name": "test op 52222222222", "oid": "99", "description": "testing", "returntype": "test", "parameters": [ { "oName": "Param1", "name": "Param1", "pid": "011", "type": "582", "description": "testing", "value": "" } ] } ] } ] 

即使唯一我想要的是个人参数。 有什么办法可以做到这一点?

你可以使用这个aggregation framework

 var oid = "99", pipeline = [ { $match: { "operations.oid": oid } }, { $unwind: "$operations" }, { $match: { "operations.oid": oid } }, { $unwind: "$operations.parameters" }, { $project: { "parameters": "$operations.parameters" } } ]; collection.aggregate(pipeline).toArray(function(error, result) { if (error) { console.log('Error retrieving parameter: ' + error); res.send({'error':'An error has occurred'}); } else { // console.log(result); res.send(result); } }); 

输出

  [ { "_id" : "04", "parameters" : { "oName" : "Param1", "name" : "Param1", "pid" : "011", "type" : "582", "description" : "testing", "value" : "" } }, { "_id" : "04", "parameters" : { "oName" : "Param2", "name" : "Param2", "pid" : "012", "type" : "58222", "description" : "testing", "value" : "" } } ] 

编辑

要访问给定pid值的单个参数,可以通过在$unwind$project阶段之间添加$matchpipe道阶段来修改pipe道,以便可以过滤文档以返回匹配pid的参数对象:

 var oid = "99", pid = "011", pipeline = [ { $match: { "operations.oid": oid } }, { $unwind: "$operations" }, { $match: { "operations.oid": oid } }, { $unwind: "$operations.parameters" }, // This pipeline stage returns the individual parameters object that matches the given pid value { $match: { "operations.parameters.pid": pid } }, { $project: { "parameters": "$operations.parameters" } } ]; 

输出

 [ { "_id" : "04", "parameters" : { "oName" : "Param1", "name" : "Param1", "pid" : "011", "type" : "582", "description" : "testing", "value" : "" } } ]