简体   繁体   中英

How to Use MySQL and MongoDb together

I am planning of using MongoDB for my comments function. But all the user's data is in MySQL. That means, I am trying to store comments in MongoDB and other fix information in MySQL. But when I started to think about retrieving comments from MongoDB, I came across the question that, how can I relate MongoDB data with MySQL. For example, user name, profile_url is stored in MySQL comments are stored in MongoDB with user_id

So how can I retrieve data like

| name  | profile_url  | comments              |
|-------|--------------|-----------------------|
| xyz   | image.jpg    | That was nice comment |
| abc   | image.jpg    | I agree               |

Is it possible to do so? Or is there any other way?

and I am using Laravel 5 with jenssegers/laravel-mongodb package.

You can't retrieve the user and comments data in the same time. You have to:

  • get the user ID
  • query mongodb using the user ID as parameter and get the comments you need

If you need aggregate data for more users, you could consider to aggregate the queries:

  • get all the users' data from mysql
  • query mongodb asking all the comments of the specified users
  • merge users data with comments data in PHP

Finally: are you sure storing the comments in mongodb is the right solution in your case? Are you planning to have a so huge ammount of comments at the point that it will require to store them in an external DB ?

If you choose this way, you can consider to store the user data in mongodb too. But before doing this, plan carefully if it's the right choice for you (ie consider the queries you'll need to do, and check if the data, stored in this way, would be fit for you queries )

MongoDB and MySQL are completely separate applications. They have no way to communicate with each other except through your application. That means if a request needs data from both sources, it needs to query both separately.

But what you could do is keep redundant data in both databases. When you store a comment in MongoDB, also put the relevant user information into the Comment document. Such a duplication of information is a deadly sin in relational databases but is common practice in MongoDB. Until recently (3.2) MongoDB had no support for JOINs whatsoever, and even now it's still quite rudimentary. That means you should usually avoid storing the data you need to fulfill a request in more than one collection, even if that means that you have redundancies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM