2014-09-19 42 views
0

我的MongoDB的文档是MongoDB中找到价值关键在嵌套数组

{ 
     _id:'ghuvt6GYrs6Hhgts6uhg', 
     photos:[ 
      { 
       "photoId":"1322", 
       "title":"Life is beautiful", 
       "score":"1331322" 
      }, 
      { 
       "photoId":"1323", 
       "title":"Very Cute Dog", 
       "score":"1231726" 
      }, 
      { 
       "photoId":"1324", 
       "title":"Funny Cat", 
       "score":"1246556" 
      }, 
      { 
       ... 
       ... 
       ... 
      } 
      . 
      . 
      . 
      . 
      . 
     ] 
    } 

我要实现的是,进去photos阵列子阵列,其中photoId:"1323" 我可以

$doc_test = $collection_images->findone(
     array("_id" => new MongoId('ghuvt6GYrs6Hhgts6uhg')), 
     array("photos" => 
      array(
       '$elemMatch' => array(
        "photoId" => "1323" 
       ) 
      ) 
     ) 
    ); 
在PHP中实现它

而到结果会像[JSON]

{ 
       "photoId":"1323", 
       "title":"Very Cute Dog", 
       "score":"1231726" 
      } 

但我想匹配子阵列的密钥(指数)值,因为这将是1因为子阵列是第二从顶部在photos阵列

请建议不使用溶液地图减少

回答

0

如果没有一些客户端逻辑或对数据的小改动,您无法做到这一点。胜利的最短路径是“_id”来检索文件:

> var doc = db.images.findOne({ "_id" : "ghuvt6GYrs6Hhgts6uhg" }) 

然后扫描阵列photoId获得的“1323”

> var spot = -1 
> for (var i = 0; i < doc.photos.length; i++) { if (doc.photos[i].photoId === "1323") spot = i } 

您也可以只标记了索引阵列文件与他们的位置:

{ 
    _id:'ghuvt6GYrs6Hhgts6uhg', 
    photos:[ 
     { 
      "spot" : 0, 
      "photoId":"1322", 
      "title":"Life is beautiful", 
      "score":"1331322" 
     }, 
     { 
      "spot" : 1, 
      "photoId":"1323", 
      "title":"Very Cute Dog", 
      "score":"1231726" 
     }, 
     ... 

你为什么要寻找数组中的照片的索引?也许有更好的方法来完成同样的事情。