我有以下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
我想将嘉士伯(rowId = 2)的价格从4.80改为4.70 ......
如何运行这样的查询?
这就是我的声音,但我现在真的被困住了......
$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是显而易见的。