To remove an item from an array by index in a MongoDB document, you can use the $set operator along with the slice operator to create a new array without the specified index. However, MongoDB does not have a direct operator to remove an item by index, so you will need to use a combination of operations.
Here’s how you can do it:
- Retrieve the document to get the current array.
- Modify the array in your application code to remove the item at the specified index.
- Update the document with the modified array.
Example
Suppose you have a document in a collection called users:
{
"_id": ObjectId("1234567890abcdef12345678"),
"hobbies": ["reading", "gaming", "coding"]
}
To remove the item at index 1 (which is "gaming"), you can do the following:
// Step 1: Find the document
const user = db.users.findOne({ _id: ObjectId("1234567890abcdef12345678") });
// Step 2: Remove the item at index 1
user.hobbies.splice(1, 1); // This removes the item at index 1
// Step 3: Update the document with the modified array
db.users.updateOne(
{ _id: ObjectId("1234567890abcdef12345678") },
{ $set: { hobbies: user.hobbies } }
);
After executing these commands, the hobbies array would be updated to:
{
"hobbies": ["reading", "coding"]
}
Make sure to replace the document ID and array field name with your actual values.
