Moon
Moon

Reputation: 22565

Add New Item to an an array using MongoDB

Let's say I'm storing a collection of ids in a document as shown as below.

{
    "id": "an id",
    "post_ids": [
        "post_id 1",
        "post_id 2",
        "post_id 3",
        "post_id 4",
    ]
}

when I add a new value into the "post_ids" array, what's the best practice?

  1. Should I lock the document? Since this is very simple operation, my guess is that it would be fast enough not to interfere other requests.
  2. Do not lock it, but check if the original document has been modified before updating the document?

Upvotes: 1

Views: 108

Answers (1)

Adam Englander
Adam Englander

Reputation: 59

What you need to do will depend on your NoSQL engine but with MongoDB you would push another value on to the array. This is an example of the document above belonging to the "posters" collection:

db.posters.update(
    { id: "an id" },
    { $push: { post_ids: "post_id 5" } }
);

Upvotes: 2

Related Questions