📅  最后修改于: 2023-12-03 15:02:35.379000             🧑  作者: Mango
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.
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"
}
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"
}
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.