📜  laravel mongodb field delete (key delete) (column delete) drop - PHP Code Example(1)

📅  最后修改于: 2023-12-03 15:02:35.379000             🧑  作者: Mango

Laravel MongoDB Field Delete (Key Delete) (Column Delete) Drop - PHP Code Example

When using Laravel with MongoDB, there will be times when you need to delete a specific field (key) from a document or a column from a collection. This can be accomplished using the unset method provided by the MongoDB class.

Deleting a Field from a Document

To delete a specific field (key) from a document, you can use the unset method with the field name as the parameter. For example, if you have a users collection with a document that looks like this:

{
    "_id": ObjectId("612590e75a1ddb06e62bf6a8"),
    "name": "John Doe",
    "email": "johndoe@example.com",
    "age": 30
}

and you want to delete the age field, you can do it like this:

use MongoDB\Client;

$client = new Client;
$collection = $client->mydb->users;

$collection->updateOne(
    ['_id' => new MongoDB\BSON\ObjectID('612590e75a1ddb06e62bf6a8')],
    ['$unset' => ['age' => '']]
);

This will result in a document that looks like this:

{
    "_id": ObjectId("612590e75a1ddb06e62bf6a8"),
    "name": "John Doe",
    "email": "johndoe@example.com"
}
Deleting a Column from a Collection

To delete a column from a collection, you can use the unset method on each document in the collection. For example, if you have a users collection with documents that look like this:

{
    "_id": ObjectId("612590e75a1ddb06e62bf6a8"),
    "name": "John Doe",
    "email": "johndoe@example.com",
    "age": 30
},
{
    "_id": ObjectId("612590e75a1ddb06e62bf6a9"),
    "name": "Jane Doe",
    "email": "janedoe@example.com",
    "age": 25
}

and you want to delete the age column from all documents, you can do it like this:

use MongoDB\Client;

$client = new Client;
$collection = $client->mydb->users;

$collection->updateMany(
    [],
    ['$unset' => ['age' => '']]
);

This will result in documents that look like this:

{
    "_id": ObjectId("612590e75a1ddb06e62bf6a8"),
    "name": "John Doe",
    "email": "johndoe@example.com"
},
{
    "_id": ObjectId("612590e75a1ddb06e62bf6a9"),
    "name": "Jane Doe",
    "email": "janedoe@example.com"
}
Dropping a Collection

Finally, if you need to drop a collection entirely, you can use the drop method. For example, if you want to drop the users collection, you can do it like this:

use MongoDB\Client;

$client = new Client;
$collection = $client->mydb->users;

$collection->drop();

This will completely remove the users collection from the database.