jtomasrl
jtomasrl

Reputation: 1451

MongoDB Collections format

I need to store restaurants with their corresponding menu items, so i did something like this

{ name: 'Foo',
  menu: 
 [ { item: 'foo',
   description: '...',
   price: 20 },
 { item: 'bar',
   description: '...',
   price: 30 } ]
}

The problem is i sometimes need to access this items, but it's not easy doing this, should i instead use something like this?

{ name: 'Foo',
menu: 
{ "0": { item: 'foo',
   description: '...',
   price: 20 },
 "1": { item: 'bar',
   description: '...',
   price: 30 } }
}

I think it's cheaper to find an specific item.

Upvotes: 1

Views: 2005

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

Using embedded objects accessible via numbered keys is rarely the right approach. MongoDB has operators to facilitate accessing items within arrays that provide much better flexibility.

See the $elemMatch and $ projection operators for ways to pull out just the array element you need.

For instance, to get the 'foo' menu item from your first example doc:

db.restaurants.findOne({name: 'Foo'}, {menu: {$elemMatch: {item: 'foo'}}});

Upvotes: 1

Related Questions