Using arrays : MongoDB – How to access an object in an array on newest questions tagged arrays – Stack Overflow

I’m not able to describe my thought precisely in words, so here’s an example:

[
  {
    'description': 'fruits',
    'examples': [
      {
        'name': 'Apple',
        'color': ['red', 'green']
      },
      {
        'name': 'Banana',
        'color': 'yellow'
      }
    []
  },
  {
    'description': 'vegetables',
    'examples': [
      {
        'name': 'Tomato',
        'color': 'red'
      },
      {
        'name': 'Carrot',
        'color': 'orange'
      }
    ]
  },
  {
    'description': 'Wweets',
    'examples': [
      {
        'name': 'Chocolate',
        'color': ['brown', 'black', 'white']
      },
      {
        'name': 'Candy',
        'color': 'various'
      }
  }
]

Let’s go step by step:

If I want to see all food categories, I query by the following command

db.food.find()

I want to see the vegetables

db.food.find({ 'description': 'vegetables' })

Now let’s say I forgot how a Carrot looks like (lol). What do I do? I tried the following (Native node.js MongoDB driver):

collection.find({'examples.name': 'Carrot'}, function(err, example){
  console.log(example)
  // It still returns me the whole object!
});

As a result I expected MongoDB to return the next highest instance of the object. For example I wanted to do this.

console.log(example.color)
// 'orange'

Do you have any idea? I’m new to document oriented DBs :/

See Answers


source: http://stackoverflow.com/questions/11713386/mongodb-how-to-access-an-object-in-an-array
Using arrays : using-arrays



online applications demo