Home > Web Front-end > JS Tutorial > body text

How do I Remove a Specific Object from an Array in MongoDB?

Linda Hamilton
Release: 2024-11-01 03:43:28
Original
582 people have browsed it

How do I Remove a Specific Object from an Array in MongoDB?

MongoDB: Removing a Specific Object from an Array

In MongoDB, you can remove a specific object from an array within a document. To accomplish this, you'll need to utilize the $pull operator.

The syntax for the $pull operator when removing an entire object from an array is as follows:

{ $pull: { arrayName: { property: value } } }
Copy after login

In the provided example, you're attempting to remove the item with an id of 23 from the items array within the document with the _id of 5150a1199fac0e6910000002. However, your original approach is incorrect as you were attempting to use the pull operator on a field (id) rather than on the desired object.

To correctly remove the entire object from the array, you need to use the following query:

db.mycollection.update(
    { '_id': ObjectId("5150a1199fac0e6910000002") }, 
    { $pull: { items: { id: 23 } } },
    false, // Upsert
    true, // Multi
);
Copy after login

This query will remove the item with an id of 23 from the items array within the specified document.

The above is the detailed content of How do I Remove a Specific Object from an Array in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!