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...
room[] doesn't have it.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?
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" } } },
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With