简体   繁体   English

如何在NoSQL中查询关系?

[英]How to query relations in NoSQL?

I have decided to move my database from MySQL to Mongo because majority of the time, my data is not structured. 我决定将我的数据库从MySQL移到Mongo,因为大多数时候,我的数据不是结构化的。 And it allowed me possibilities that was too complex in a traditional SQL. 它让我在传统的SQL中过于复杂。

There is one problem that I am currently facing and how to approach a traditional relational model of SQL in NoSQL. 我目前面临的一个问题是如何在NoSQL中使用传统的SQL关系模型。 I have read many times that NoSQL is not designed to deal with relations. 我已多次读过NoSQL不是为处理关系而设计的。 Do I need to add them as an array to the document with a relation? 我是否需要将它们作为数组添加到具有关系的文档中?

Here is one situation that has made me stuck. 这种情况让我陷入困境。 In SQL I had a separate table for oauth access tokens that has user_id, client_id, access_token, expires as its attributes. 在SQL中,我有一个单独的oauth访问令牌表,其中包含user_id,client_id,access_token,expires作为其属性。 It was 1-N relation between a user and an access_token. 用户和access_token之间是1-N关系。 How would I do that in NoSQL? 我如何在NoSQL中做到这一点? By adding an array field oauth_tokens? 通过添加数组字段oauth_tokens? If I do that, how do I search for the token in the array? 如果我这样做,我如何在数组中搜索令牌? How do I query 我该如何查询

search for a document where the _id is $user_id and there is an element
with $token in the access_tokens array?

You have at least 2 options here: 这里至少有两个选项:

  1. You can store oauth_tokens in separate collection (just like you had in MySQL in other table), and add to oauth_token field like user_id containing _id value for this current user from users collection. 您可以将oauth_tokens存储在单独的集合中(就像在其他表中的MySQL中一样),并添加到oauth_token字段,例如user_id,其中包含来自users集合的当前用户的_id值。 Finding tokens for specified user is just searching in oauth_tokens collection for documents with given user_id. 为指定用户查找令牌只是在oauth_tokens集合中搜索具有给定user_id的文档。 Keep in mind that this kind of relation isn't "supported" in any way by Mongo - database will not help you keeping values of field user_id correct. 请记住,Mongo不会以任何方式“支持”这种关系 - 数据库不会帮助您保持字段user_id的值正确。

Example: 例:

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

query: 查询:

db.tokens.find({user_id:"20"})
  1. Just like you wrote: you can embedded tokens in user document and query for existing tokens. 就像你写的:你可以在用户文档中嵌入标记并查询现有标记。 Check docs to see how you can query for embedded documents: link 检查文档以了解如何查询嵌入式文档: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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