How to model many-to-many relationships in MongoDB (for a MySQL user)

后端 未结 2 1623
-上瘾入骨i
-上瘾入骨i 2021-02-08 10:04

I come from a MySQL background and am trying to wrap my head around MongoDB. In particular, I\'m struggling to conceptualize how I should model n

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 10:52

    Great question. Let me first outline a bit of how the N:N relationship works then I'll go into detail on each of your bullet points.

    N:N in MySQL normally you have your pivot table associating between your user and interests (user_interests table). In mongo you do this a bit differently. You still have a users and interest collection, however instead now, you store a list of keys under interests for a user. SO something like this:

    User Collection {
          "name":"Josh",
          "user":"jsmith",
          "interests":[
               {
                "_id":12345,
                "rating":"like"
               },
               {..}..
          ]
    }
    

    By storing your interests in a list which is keyed off on your interest table, you can perform each of the actions you require. If you wanted to do a query you'd od it based on the ID which is in the interest table then do a query using the $in modifier.

    Now for your interests collection I'd do the following:

    User Interest {
          "_id":objectId
          "label":"Swimming",
          "count":intValue
    }
    

    When adding an interest to a users document, the count variable would then depend on the definition of your ratings. If you're storing your ratings in a separate area (or in logic), then the value you assigned to them would be what you relate then to the int value in interest. IE: User rates it meh (which has a value of 1) then you would add 1 to the count value.

    Hopefully this is helpful and has at the very least brought about some other ideas on how to structure it!

    Best of luck, remember MONGO IS AWESOME.

提交回复
热议问题