开发者

Question about MongoDB from a SQL user

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 m开发者_开发知识库e :)


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.


  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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜