How to enforce foreign keys in NoSql databases (MongoDB)?

后端 未结 6 685
暗喜
暗喜 2020-11-28 15:31

Let\'s say I have a collection of documents such as:

{ \"_id\" : 0 , \"owner\":0 \"name\":\"Doc1\"},{ \"_id\" : 1 , \"owner\":1, \"name\":\"Doc1\"}, etc
         


        
6条回答
  •  广开言路
    2020-11-28 16:12

    This is a one-to-one to relationship. It's better to embed one document in another, instead of maintaining separate collections. Check here on how to model them in mongodb and their advantages.

    Although its not explicitly mentioned in the docs, embedding gives you the same effect as foreign key constraints. Just want to make this idea clear. When you have two collections like that:

    C1:

    { "_id" : 0 , "owner":0 "name":"Doc1"},{ "_id" : 1 , "owner":1, "name":"Doc1"}, etc
    

    C2:

    { "_id" : 0 , "username":"John"}, { "_id" : 1 , "username":"Sam"}
    

    And if you were to declare foreign key constraint on C2._id to reference C1._id (assuming MongoDB allows it), it would mean that you cannot insert a document into C2 where C2._id is non-existent in C1. Compare this with an embedded document:

    {
        "_id" : 0 , 
        "owner" : 0,
        "name" : "Doc1",
        "owner_details" : {
            "username" : "John"
        }
    }
    

    Now the owner_details field represents the data from the C2 collection, and the remaining fields represent the data from C1. You can't add an owner_details field to a non-existent document. You're essentially achieving the same effect.

提交回复
热议问题