Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update and insert new element in array in MongoDB

Tags:

mongodb

I am new to MongoDB. I want to store User data in an array. The data is single unique document.lets say the document is like this.

User { id: number, name: string }
{
  _id : 001,
  room: User[],
}

I want to do something this...

  • push element (User) if room[] doesn't have it.
  • update User data.

Like there is upsert option in update operation.

  DB.Collection.updateOne(
      { _id: "001" },
      { $set: { name: "Bar" } },
      { upsert: true }
    );

How can I do something like this,In an Array of a Document?

like image 380
Stone Avatar asked Oct 18 '25 15:10

Stone


1 Answers

You can use $set operation to update Embedded Document with $(update) or $[$[<identifier>].But It's not work good with upsert So in order insert new Document use $push.Do something to update data or append data separately.

// push element (User) if room[] doesn't have it.

DB.Collection.updateOne(
    { "room.id": { $ne: "001" } },
    { $push: { "room": { id: "001", name: "Bar" } } },
);

// update User data

DB.Collection.updateOne(
    { "room.id": "001"  },
    { $set { "room.$": { id: "001", name: "Foo" } } },
);


like image 76
Nur Avatar answered Oct 22 '25 04:10

Nur