Reputation: 357
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},
});
Upvotes: 0
Views: 316
Reputation: 61273
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},
});
Upvotes: 3
Reputation: 1664
In your query, in the "find" part, you have to specify what you are looking in your array. Per example: "suggestions.name" = "Vote1"
Upvotes: 0