Fernando Rivero
Fernando Rivero

Reputation: 103

Remove element inside array in MongoDB using PHP

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)); 

Upvotes: 1

Views: 233

Answers (1)

Mehdiable
Mehdiable

Reputation: 94

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.

Upvotes: 1

Related Questions