2015-04-14 3 views
1

Так у меня есть 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": "" 
        } 
       ] 
      } 
     ] 
    } 
] 

Я хочу, чтобы быть в состоянии найти все параметры и индивидуален, но я не совсем уверен, как, если я использую это:

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": "" 
        } 
       ] 
      } 
     ] 
    } 
] 

, хотя единственное, что я хочу, это индивидуальная вол ameter. Есть ли способ сделать это?

ответ

1

Вы можете использовать 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" : "" 
      } 
     } 
    ] 

EDIT:

Для доступа к отдельному параметру, задаваемому значением pid, вы можете изменить трубопровод, добавив $match этап трубопровода между $unwind и $project этапов, так что вы можете отфильтровать документы для возврата соответствия объекта параметр 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" : "" 
     } 
    } 
] 
+1

Это именно то, что мне было нужно, спасибо , Как бы вы изменили это, если вам нужен только отдельный параметр? У меня есть доступ к pid через req.params.parameters –

+0

@SantiagoEsquivel Не стоит беспокоиться :-) Я изменил свой ответ, чтобы адресовать эту часть. – chridam

+1

Thats amazing, я не могу вас поблагодарить достаточно, я боролся с этим последним бит в моей программе много последних дней пары. –

Смежные вопросы