Home > OS >  How to remove data in object from MongoDB document
How to remove data in object from MongoDB document

Time:08-13

The object contains the username and category. Categories is another object that contains categories and costs. How can I remove all key-values ​​in a category object? Now in my code, using deleteOne() I find all the fields of the object named "Bob". I am deleting the entire document named "Bob". And I need to clear the categories in this document, for example, deleteOne({ name: "Bob", category }, and have { name: "Bob", category: {} } output to the console

let users = [
  {
    name: "Bob",
    сategories: {
      eat: "20$",
      entertainment: "100$",
    },
  },
];

mongoClient.connect(function (err, client) {
  if (err) return console.log(err);
  const db = client.db("expensesdb");
  db.collection("users").deleteOne({ name: "Bob" }, function (err, result) {
    console.log(result);
    client.close();
  });
});

CodePudding user response:

You can use updateOne method to set сategories as empty object using $set or you can use $unset to unset your сategories data.

  • Related