Home > Web Front-end > JS Tutorial > How to Remove an Object from an Array in MongoDB?

How to Remove an Object from an Array in MongoDB?

Susan Sarandon
Release: 2024-11-03 18:32:29
Original
743 people have browsed it

How to Remove an Object from an Array in MongoDB?

Removing an Object from an Array in MongoDB

When dealing with documents that contain arrays, it may be necessary to remove specific objects from them. This is commonly seen with documents that store a list of items or similar entries. In MongoDB, there is a designated operator, known as $pull, specifically designed for this purpose.

The example provided illustrates a document with an array of items. The goal is to remove the item object with id equal to 23. The initial attempt to use $pull is incorrect, as it attempts to match on the id field directly within the $pull statement, which is not the correct syntax.

To successfully remove the desired object, the correct query is:

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

This query specifies that it wants to update the document with the given _id, and in that update, it applies the $pull operator to the items array, matching each array element with an id of 23.

For those using Mongoose/Node.js, the equivalent code snippet is:

<code class="javascript">Model.updateOne(
    { '_id': ObjectId("5150a1199fac0e6910000002") }, 
    { $pull: { items: { id: 23 } } },
    function(err, result) {
        // Handle error or result
    }
);</code>
Copy after login

The above is the detailed content of How to Remove an 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