Question

I'm following the example in the docs:

> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",
  "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }

> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )

> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",
  "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }

This shows how you can search for Joe's votes count and increment it. What I'd like to accomplish is incrementing Jane's votes count when querying for Joe's. In my case, comments is an array always of length 2. Perhaps it's best showed with my current (non-working) syntax:

t.update( {'comments.by':'joe'}, {$inc:{'comments[1-$].votes':1}}, false, true )

I thought $ would be 0 here because Joe is first in the array. To get the other array index, I assumed 1-$ would do the job, but it doesn't.

How can one match the other array element than the one queried for?

Was it helpful?

Solution

No, this is not possible. $ points to first matched element in the array. You can't build references to other elements that are relative to that matched element. You can always use absolute references, though (comments.1.votes).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top