0

我有以下 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)));

它不漂亮,但它有效,我不必改变我的结构。

4

1 回答 1

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 是显而易见的。

于 2012-11-02T12:23:11.440 回答