MongoDB在嵌套数组中按值查找键

时间:2014-09-19 21:30:24

标签: php arrays 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"     我可以用php实现它

$doc_test = $collection_images->findone(
        array("_id" => new MongoId('ghuvt6GYrs6Hhgts6uhg')),
        array("photos" => 
            array(
                '$elemMatch' => array(
                    "photoId" => "1323"
                )
            )
        )
    );

结果看起来像[JSON]

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

但是我想要匹配的子数组的键(索引)值,因为它是1,因为该子数组在photos数组中位于第二位

请在不使用map-reduce的情况下建议解决方案

1 个答案:

答案 0 :(得分: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"
        },
        ...

为什么要查找阵列中照片的索引?也许有更好的方法来完成同样的事情。

相关问题