xxxxxxxxxx
> db.removeArrayElementByItsIndexDemo.update({}, {$unset : {"InstructorSubject.2" : 1 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
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
xxxxxxxxxx
db.example.update({}, [
{$set: {field: {
$concatArrays: [
{$slice: ["$field", P]},
{$slice: ["$field", {$add: [1, P]}, {$size: "$field"}]}
]
}}}
]);