Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about MongoDB from a SQL user

Tags:

mongodb

nosql

I have very interested in using MongoDB it seems awesome. But I'm from a totally different school : relational databases.

So now I'm wondering how would this case works with MongoDB:

Say, I have a table filled with brands and I have another table filled with products.

Each products will have a brand. This is very simple to understand but I still don't get how would this works with MongoDB?

I mean, would I have to repeat the brand each time I add a product? Can I do some kind of relations?

Thanks for enlightening me :)

like image 268
Tommy B. Avatar asked Sep 12 '26 22:09

Tommy B.


2 Answers

One way would be to set it up similar to this:

{'brand':'brand one', 'products':
                       [{'product name':'a fine product','price':'$50'},
                        {'product name':'yet another fine product','price':'$20'}]
},
{'brand':'brand two', 'products':
                       [{'product name':'brand two product','price':'$10'}]
}

In this case you only have one 'table' with all the information you need on the products (including brand). I have only done some experimenting with mongodb so I'm not sure how this would scale.

It is a different way of thinking from a relational DB and a nosql solution shouldn't be used in all cases.

like image 128
sriehl Avatar answered Sep 15 '26 11:09

sriehl


  1. Insert brands
  2. Insert insert products (with brands)
  3. Query it

Preparation:

  • Download http://www.mongodb.org/downloads
  • On Windows create dir c:\data\db\ (the default dir, don't care much about it now)
  • Run mongod (it will run a server)
  • Run mongo (it will run a client and use default test database)

Brands:

db.things.save({'name': 'Ford'});
db.things.save({'name': 'Mitsubishi'});

Products:

db.things.save({'brand': 'Ford', 'name': 'Mustang'});
db.things.save({'brand': 'Ford', 'name': 'Falcon'});
db.things.save({'brand': 'Mitsubishi', 'name': 'Delica'});
db.things.save({'brand': 'Mitsubishi', 'name': 'L300'});

Querying:

db.things.find();
db.things.find({'brand': 'Ford'});
db.things.find({'brand': 'Mitsubishi'});

// I just learned this (incl. downloading etc) almost before the first answer was posted from tutorial and manual in general. Nice experience :)

like image 35
dwich Avatar answered Sep 15 '26 10:09

dwich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!