簡體   English   中英

MongoDB通過嵌套數組中的值查找鍵

[英]MongoDB find key by value in nested array

我的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的解決方案

如果沒有一些客戶端邏輯或對數據進行少量更改,就無法做到這一點。 取得勝利的最短途徑是通過“ _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"
        },
        ...

為什么要在陣列中尋找照片的索引? 也許有更好的方法可以完成同一件事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM