0

Let's say there is a data structure containing objects like

{ 
  name : 'ernie',
  likes : [
  {
    what : 'rubber duckie',
    howmuch : 5
  },
  {
    what : 'bert',
    howmuch : 3
  }]
}

and

{ 
  name : 'cookie monster',
  likes : [
  {
    what : 'cookies',
    howmuch : 100
  }]
}

If the 0th element of ernie's likes-array should have its howmuch-value incremented, say, by 1, is there a MongoDB command to do this? The JavaScript-equivalent would be ernie.likes[0].howmuch++.

Specifically, can you access the elements of an array by index number?

serv-inc
  • 35,772
  • 9
  • 166
  • 188

2 Answers2

1

To increment the howmuch field value by 1 of the 0th element of ernie's likes-array, use the $inc operator together with the dot notation to access the element of the array by the zero-based index position:

db.collection.update(
    {
        "name": "ernie"       
    }, 
    { 
        "$inc" : { "likes.0.howmuch" : 1 } 
    }
)
chridam
  • 100,957
  • 23
  • 236
  • 235
0

do you want to create index on array? if yes, you have to create index on 'likes' array. with this code : db.sample.createIndex ({likes : 1}) . or more specifically, you have to create db.sample.createIndex ({'likes.howmuch': 1})

After index creation, you can access array elements with index.

trallallalloo
  • 592
  • 1
  • 9
  • 25
  • I did not want to create an index. (the wording is unfortunate, though). The question asks for a **mongo equivalent of `ernie.likes[0].howmuch++`**. (If you want to edit the question to make this more clear, feel free) – serv-inc Sep 18 '15 at 08:20
  • 2
    first version, I understood that you need an index, sorry. @chridam's answer is right. – trallallalloo Sep 18 '15 at 08:24