Home > database >  How can I remove a single element from a mongoDB document?
How can I remove a single element from a mongoDB document?

Time:11-30

I have this code :

from admin import *
grab_data = tasks_collection.find()

class Habits:
    def __init__(self):
        self.default = False
        self.habits = {}

    def add_habit(self, habit_name, habit_difficulty=0):
        self.habits[habit_name] = [self.default, habit_difficulty]

    def remove_habit(self, habit_name):
        del self.habits[habit_name]

    def plus_habit(self):
        pass

    def minus_habit(self):
        pass

    def add_data(self):
        habits_collection.insert_one(self.habits)


class Tasks:
    def __init__(self):
        self.default = False
        self.tasks = {}

    def add_task(self, task_name, task_difficulty=0):
        if task_name not in self.tasks:
            self.tasks[task_name] = [self.default, task_difficulty]
        else:
            print(f"Task '{task_name}' already exists.")

    def show_task(self):
        return self.tasks

    def remove_task(self, task_name):
        del self.tasks[task_name]


    def add_data(self):
        tasks_collection.insert_one(self.tasks)


task = Tasks()

task.add_task("clean room")

task.add_task("study")
task.add_task("study")

task.add_task("be lazy")
task.add_data()

Which basically is used to create a ToDo dictionary with tasks and then add them into my database. So far so good. But how can I delete a single task from the database ? When I read the data from the database I get this:

{'_id': ObjectId('61a60bbd13d0ccf4e9bb300d'), 'clean room': [False, 0], 'study': [False, 0], 'be lazy': [False, 0]}

I have tried to remove it like this :

for data in grab_data:
    for key, value in data.items():
        if key == "be lazy":
            tasks_collection.delete_one({key: value})

But it removes the whole dictionary. How can I only remove "be lazy"?

CodePudding user response:

You can use projection stage when get the data from DB to not output some fields:

db.collection.find({},
{
  "be lazy": 0
})

Example here

CodePudding user response:

You want to be using the $unset update operator, like so:

db.collection.update_many({
  "be lazy": {"$exists": True}
},
{
  "$unset": {
    "be lazy": ""
  }
})

Mongo Playground

  • Related