Home > Enterprise >  How to add a field to a MongoDB object
How to add a field to a MongoDB object

Time:08-12

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();
    }
  );
});

CodePudding user response:

Use dot notation

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

Playground

CodePudding user response:

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();
    }
  );
  • Related