How to request relationships in NoSQL?

I decided to migrate my database from MySQL to Mongo because most of the time my data is not structured. And that allowed me features that were too complex in traditional SQL.

There is one problem that I am currently facing, and the approach to the traditional relational SQL model in NoSQL. I read many times that NoSQL is not intended for relationships. Do I need to add them as an array to a document with a relation?

Here is one of the situations that made me stuck. In SQL, I had a separate table for oauth access tokens, which have user_id, client_id, access_token, expire as its attributes. This was a 1-N relationship between user and access_token. How do I do this in NoSQL? By adding an oauth_tokens array field? If I do, how can I search for a marker in an array? How to request

search for a document where the _id is $user_id and there is an element with $token in the access_tokens array? 
+5
source share
1 answer

You have at least 2 options:

  • You can store oauth_tokens in a separate collection (as in MySQL in another table), and add in the oauth_token field, for example user_id, containing the _id value for this current user from the user collection. The search for tokens for the specified user is simply a search in the oauth_tokens collection for documents with the given user_id. Keep in mind that this relationship is not supported by "Mongo" in any way - the database will not help you store the values โ€‹โ€‹of the user_id field correctly.

Example:

 db.tokens.insert({ client_id : "1", user_id : "20", access_token : "1234567890", expires : new Date(2014-12-31)}) 

inquiry:

 db.tokens.find({user_id:"20"}) 
  1. Just as you wrote: you can insert tokens into a user document and request existing tokens. Check the documents to see how you can request embedded documents: link
+2
source

Source: https://habr.com/ru/post/1202943/


All Articles