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

How to Remove a Specific Object from an Array in MongoDB?

DDD
DDDOriginal
2024-11-02 07:26:291043browse

How to Remove a Specific Object from an Array in MongoDB?

MongoDB: Removing an Object from an Array

Problem:

In MongoDB, how do you extract a specific object from an array embedded within a document? In the example document, we want to remove the object with id: 23 from the items array.

Solution:

To achieve this, use the $pull operator with a more specific query to match the desired object within the array.

MongoDB Query:

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

Explanation:

  • $pull operator: Used to remove an element from an array.
  • { items: { id: 23 } }: Specify the nested object to remove by matching its specific field.
  • Upsert: Set to false to prevent creating a new document if the update doesn't match any existing document.
  • Multi: Set to true to apply the update to multiple matching documents (although there should only be one match in this case).

Node.js/Mongoose:

In Mongoose, you can use the following query:

<code class="javascript">MyModel.findOneAndUpdate(
  { '_id': '5150a1199fac0e6910000002' },
  { $pull: { items: { id: 23 } } },
  { multi: true }
);</code>

Note: MongoDB 3.6 also supports the $elemMatch operator in conjunction with $pull for more complex filtering within arrays.

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

Statement:
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