1

I have this structure in mongoDB and I want to remove all "Vespertino" elements using PHP:

{"_id": ObjectId("5a186d574b23328df3be"),"monday": [
"Vespertino",
"Matutino"],"tuesday": [
"Test1",
"Matutino"],"wednesday": [
"Vespertino",
"Test2"],"thursday": ["Test3","Matutino"],"friday": ["Vespertino","Matutino"],"saturday": ["Matutino"],"sunday": [],"id":"30334798","c_code": "my_company"}

I was trying to get results in first place and then remove the element but I get only null results, this was my attempt until now:

$query_shifts = array('c_code'=>"my_company","wednesday.Vespertino"=> array('$exists' => true)); 
2
  • Take a look: stackoverflow.com/questions/369602/… , try to use array_slice or unset Commented Feb 25, 2019 at 20:03
  • oh no no @MiguelCruz, I need to remove the elements from MongoDB document. Thanks anyway. Commented Feb 25, 2019 at 20:06

1 Answer 1

1

mongodb query is :

db.CollectionName.update({"_id": ObjectId("5a186d574b23328df3be")}, {
    {$pull: {monday: "Vespertino", tuesday: "Vespertino", wednesday: "Vespertino", thursday: "Vespertino", friday: "Vespertino", saturday: "Vespertino", sunday: "Vespertino"} },
    { multi: true }
});

in PHP :

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(["_id" => new MongoDB\BSON\ObjectId("5a186d574b23328df3be")], [$pull => ['monday' => "Vespertino", 'tuesday' => "Vespertino", 'wednesday' => "Vespertino", 'thursday' => "Vespertino", 'friday' => "Vespertino", 'saturday' => "Vespertino", 'sunday' => "Vespertino"]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('dbName.CollectionName', $bulk);

I hope to help you.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! your solution works perfect! This is my final code in PHP: $r = $col->update(array('c_code'=>"my_company"),array('$pull'=>array('monday'=>"vespertino",'tuesday'=>"vespertino",'wednesday'=>"vespertino",'thursday'=>"vespertino",'friday'=>"vespertino",'saturday'=>"vespertino",'sunday'=>"vespertino")),array('multiple' => true) );
Yes; Your final code is correct for remove all of the 'vespertino' items from all documents of your collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.