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

How do I remove an object from an array in MongoDB?

Susan Sarandon
Release: 2024-11-01 02:29:02
Original
316 people have browsed it

How do I remove an object from an array in MongoDB?

MongoDB: Removing an Object from an Array

In MongoDB, you can remove an object from an array embedded in a document using the $pull operator. If you wish to remove a specific object from an array, you need to provide a query that matches the exact object.

Consider the following document:

<code class="json">{
   _id: 5150a1199fac0e6910000002,
   name: 'some name',
   items: [{
      id: 23,
      name: 'item name 23'
   },{
      id: 24,
      name: 'item name 24'
   }]
}</code>
Copy after login

To remove the item with id: 23 from the items array, use the following command:

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

This command updates the document by removing the item from the array. The query specifies the document using the _id field, and the $pull operator targets the items array. Within the $pull operation, you can specify a query to match the object to be removed. In this case, we match the object with id: 23.

Mongoose/Node.js Implementation

In Mongoose, you can remove an object from an array using the pull() method:

<code class="javascript">const Model = mongoose.model('Model', new mongoose.Schema({
  items: [{
    id: Number,
    name: String
  }]
}));

Model.update(
  { '_id': '5150a1199fac0e6910000002' },
  { $pull: { items: { id: 23 } } },
  { multi: true }, // Update all matching documents
  (err, result) => { if (!err) console.log(result); }
);</code>
Copy after login

This code will remove the item with id: 23 from the items array of all documents that match the specified _id.

The above is the detailed content of How do I 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