xxxxxxxxxx
db.getCollection('profilesservices').updateOne({_id: ObjectId("60391a9eefdb7c17bd84c0b1")},
{
$pull: { "volunteerExperiences": {_id: ObjectId("60392e7595bb2d87689aca62")} }
}
)
xxxxxxxxxx
const mongoose = require('mongoose');
// Define your schema
const mySchema = new mongoose.Schema({
myArray: [String] // Replace "String" with the actual type of the elements in your array
});
// Create your model
const MyModel = mongoose.model('MyModel', mySchema);
// Remove an item from the array by index using a MongoDB query
const removeItemByIndex = async (documentId, arrayIndex) => {
try {
await MyModel.updateOne({ _id: documentId }, { $unset: { [`myArray.${arrayIndex}`]: 1 } });
console.log('Item removed successfully.');
} catch (error) {
console.error(error);
}
};
// Usage
removeItemByIndex('documentId', 2); // Replace 'documentId' with the actual ID of the document and '2' with the index of the item you want to remove