开发者

$pull single array element

I would like to be able to remove array element [1] for service and charged. the problem is that anytime other elements

contain identical values, all elements are removed ie. [1]-[8] and [10]-[15]. I have tried to limit this by specifing the

element identifier in brackets, and that doesn't work either.

If there are no duplicate values, the following code works perfectly. I can remove [1] and [9] with no problems.

$forward = $_POST['id'];
$conn = new Mongo('localhost');
$db = $conn->pianos;
$collection = $db->names;
$criteria = array('_id' => $forward,);


// Find single document by ID Variable 
$obj = $collection->findOne($criteria);


// define variables for Array objects
$service = $obj['service'] [$i];
$charge = $obj['charge'] [$i];

$serv = array('service' => $service, 'charge' => $charge);

$upsert = true; 
        $collection->update($obj, array('$pull' => $serv) ,array("upsert" =>   $upsert));               

The structure for a document as provided by PhpMoAdmin is listed below.

[$_id] => MongoID Object (
  [$id] => 4e3a8a457bfb8b2817000002
)

[fname] => Billy Bob
[lname] => Thornton

[service] => Array (
[0] => Tune 2 pianos
[1] => Tuned
[2] => Tuned
[3] => Tuned
[4] => Tuned
[5] => Tuned
[6] => Tuned
[7] => Tuned
[8] => Tuned
[9] => Called
[10] => Tuned
[11] => Tuned
[12] => Tuned
[13开发者_如何学运维] => Tuned
[14] => Tuned
[15] => Tuned
)
[charged] => Array (
[0] => 100.00
[1] => 50.00
[2] => 50.00
[3] => 50.00
[4] => 50.00
[5] => 50.00
[6] => 50.00
[7] => 50.00
[8] => 50.00
[9] => 0.00
[10] => 50.00
[11] => 50.00
[12] => 50.00
[13] => 50.00
[14] => 50.00
[15] => 50.00
)


MongoDB doesn't have modifier operation for this.

You could add a service date for all of the entries so all of them would become unique. Also, from a design perspective it would be better to store in the array sub-documents which contain the service name, data & charge (and whatever you add later).

With the current "schema" the only thing you can do is to retrieve the whole document, fix it on the client side and write it back. This is not going to be atomic so make sure that only there is only one user who can modify a document at a specific time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜