0

I am trying to update an object inside of an array. Here is my structure:

"_id": "ubtQP9EjmxhXS5z98",
  "name": "My Data",
  "desc": "What songs should I play at my wedding?",
  "private": false,
  "suggestions": [
    {
      "name": "Vote 1",
      "link": "http://www.website.com/",
      "votes": 0
    },
    {
      "name": "Vote 2",
      "votes": 0
    }
  ],
  "author": "tovd9Win3C3fntgyR",
  "createdAt": "2016-01-10T08:36:37.014Z"

I want to update the votes on the first object in "suggestions" by 1. At the moment I have the following code but it does NOT work.

Polls.update("ubtQP9EjmxhXS5z98", {
    $inc: {suggestions.$.votes: 1},
});

2 Answers 2

3

If you know the array index of the embedded document, you can specify the document using the embedded document’s position using the dot notation.

You don't need the positional $ update operator here because you know the position of the element you want to update.

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

Also to use the $ operator the array field must appear as part of the query document.

Polls.update({"_id": "ubtQP9EjmxhXS5z98"}, {
    "$inc": {"suggestions.1.votes": 1},
});
Sign up to request clarification or add additional context in comments.

Comments

0

In your query, in the "find" part, you have to specify what you are looking in your array. Per example: "suggestions.name" = "Vote1"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.