skip to Main Content

Application to control expenses. I write an object to a collection in the MongoDB database which contains the username and another object – the categories for which he spent money. How can I add one category to the categories object? I tried via findOneAndUpdate but it overwrites all categories and you need to specify all categories to search. How can I write one category to a user’s categories object?

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

mongoClient.connect(function (err, client) {
  if (err) return console.log(err);

  const db = client.db("expensesdb");
  const col = db.collection("users");
  col.findOneAndUpdate(
    {
      сategories: {
        eat: "20$",
        entertainment: "100$",
      },
    },
    {
      $set: {
        сategories: {
          products: "100$",
        },
      },
    },
    function (err, result) {
      console.log(result);
      client.close();
    }
  );
});

2

Answers


  1. Use dot notation

    db.collection.update({
      "сategories": {
        eat: "20$",
        entertainment: "100$",
        
      },
      
    },
    {
      $set: {
        "сategories.products": "100$"
      },
      
    })
    

    Playground

    Login or Signup to reply.
  2. Modify your query using dot notation.

     col.findOneAndUpdate(
        {
          сategories: {
            eat: "20$",
            entertainment: "100$",
          },
        },
        {
          $set: {
            "сategories.products": "100$",
          },
        },
        function (err, result) {
          console.log(result);
          client.close();
        }
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search