2012-11-02 35 views
0

我有以下MongoDB的對象:的MongoDB:被困在複雜的查詢...更新對象內部的數組

{ 
    "_id": ObjectId("508ec9f413f88da4a590e5ee"), 
    "beersAndStouts": { 
    "0": { 
     "description": "Guinness", 
     "price": "4.20" 
    }, 
    "1": { 
     "description": "Heineken", 
     "price": "4.80" 
    }, 
    "2": { 
     "description": "Carlsberg", 
     "price": "4.80" 
    } 
    }, 
    "snacks": { 
    "0": { 
     "description": "King cheese and onion", 
     "price": "2.20" 
    }, 
    "1": { 
     "description": "Tayto cheese and onion", 
     "price": "1.80" 
    } 
    }, 
    "specialOffers": { 
    "0": { 
     "description": "Two for one vodka\/red bull", 
     "price": "8" 
    } 
    }, 
    "uname": "Eamorr", 
    "wines": { 
    "0": { 
     "description": "Cabernet Sauvignon", 
     "price": "5.00" 
    }, 
    "1": { 
     "description": "Chardonnay", 
     "price": "5.00" 
    } 
    } 
} 

,我有以下的PHP變量:

$category=$_POST['category']; //"beersAndStouts" 
$description=$_POST['columnName']; //"Description" 
$value=$_POST['value']; //"4.70" 
$rowId=$_POST['rowId']; //2 

我想將Carlsberg(rowId = 2)的價格從4.80改爲4.70 ...

如何運行這樣的查詢?

這裏是我有SOFAR,但我現在真的卡住...

$priceLists=$mongo->eamorr->priceLists; 
$priceLists->update(array('uname'=>$uname),array('$set'=>array($category=>array($rowId=>xxx)))); 

更新:這裏是我使用的代碼:

$mongo=new Mongo(); 
$priceLists=$mongo->eamorr->priceLists; 

$priceList=$priceLists->findOne(array('uname'=>$uname)); 

$newCategory=$priceList[$category]; 
$newCategory[$rowId][$description]=$value; 

$priceLists->update(array('uname'=>$uname),array('$set'=>array($category=>$newCategory))); 

這不是漂亮,但它有效,我不必改變我的結構。

+0

這裏設置了什麼? –

回答

2

爲什麼你需要它作爲對象的對象? 您可以使用對象的數組代替它,在這種情況下,它會工作得很好 這裏的理念是:

{ 
    "_id" : ObjectId("508ec9f413f88da4a590e7ee"), 
    "beersAndStouts" : [{ 
     "description" : "Guinness", 
     "price" : "4.20" 
    }, { 
     "description" : "Heineken", 
     "price" : 6666 
    }, { 
     "description" : "Carlsberg", 
     "price" : "4.80" 
    }], 
    "snacks" : [{ 
     "description" : "King cheese and onion", 
     "price" : "2.20" 
    }, { 
     "description" : "Tayto cheese and onion", 
     "price" : "1.80" 
    }], 
    "specialOffers" : [{ 
     "description" : "Two for one vodka/red bull", 
     "price" : "8" 
    }], 
    "uname" : "Eamorr", 
    "wines" : [{ 
     "description" : "Cabernet Sauvignon", 
     "price" : "5.00" 
    }, { 
     "description" : "Chardonnay", 
     "price" : "5.00" 
    }] 
} 

而在這樣的情況下,查詢很簡單:

db.test.update({ 
    "_id" : ObjectId("508ec9f413f88da4a590e7ee"), 
    "beersAndStouts.description" : "Carlsberg" 
},{ 
    '$set' : { 
    'beersAndStouts.$.price' : 4.70 
} 
}); 

保持記住我改變了ObjectId!

把它放在你的mongo shell中,它可以工作。

我希望調整到PHP是顯而易見的。

+0

是的,對象的對象是多餘的......我將不得不再看看我如何存儲這些信息。非常感謝你的回覆。 – Eamorr