Understand the basic use of mongodb foreign key

Time:2020-9-19

Small continue to learn, the content of this study is the basic use of mongodb foreign key.

Methods for representing table relationships

In the traditional relational database, the table relation is represented, and the data is improved by index.
In mongodb, table relation is represented by nesting, that is, a document is nested as the association of two documents in mongodb, and reference link is used as the association between documents.

Document nesting

Using visual

The visual editor is used here as document nesting
Enter the following document object

{
    "ming": "ming",
        "ming2": {
            "ming3": "ming8"
        }
}

Understand the basic use of mongodb foreign key

After the insertion is successful, it is as follows
Understand the basic use of mongodb foreign key

This completes the nesting of documents, that is, represents an association between two documents.

Using JDK

The JDK is used to connect here.
Add dependencies first

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.5.0</version>
</dependency>

Connect

try{   
       //Connect to mongodb service
         MongoClient mongoClient = new MongoClient( "106.53.115.12" , 27017 );
       
         //Connect to database
         MongoDatabase mongoDatabase = mongoClient.getDatabase("koa");  
       System.out.println("Connect to database successfully");
        
      }catch(Exception e){
        System.err.println( e.getClass().getName() + ": " + e.getMessage() );
     }

Insert

List<Document> collections = new ArrayList<Document>();
Document d1 = new Document();
D1. Append ("name", "Romance of the Three Kingdoms"). Append ("author", "Luo Guanzhong");
Document d2 = new Document();
D2. Append ("name", "dream of Red Mansions"). Append ("author", D1);
collections.add(d2);
c.insertMany(collections);

The query data are as follows

{
    "Name": a dream of Red Mansions,
    "author": {
        "Name": the romance of the Three Kingdoms,
        "Author": Luo Guanzhong
    }
}

At this point, the nesting operation of the document is completed

Foreign key query

Using JS language, query Association

Here, we use new dbref to do foreign key query.
At this point, for dbref, there are the following fields.

$ref

         The $ref field contains the name of the collection where the referenced document is located.

$id

        The $ID field contains_ ID refers to the value of the field in the document.

$db

      Optional. Contains the name of the database where the referenced document is located. Only some drivers support the $DB reference, which indicates that it can be associated across collections

Here, the set operations are associated as follows

//Save the data of the collection
> var a={value:"1"}  
 
> var b={value:"2"}  
 
> var c={value:"9"}  
 
> var d={value:"10"}  
 
> db.A.save(a)  
 
> db.A.save(b)        
 
> db.A.save(c)   
 
> db.A.save(d)  
 //Query the collection data
> db.A.find()                                                                                                 
 
{ "_id" : ObjectId("4e3f33ab6266b5845052c02b"), "value" : "1" }  
 
{ "_id" : ObjectId("4e3f33de6266b5845052c02c"), "value" : "2" }  
 
{ "_id" : ObjectId("4e3f33e06266b5845052c02d"), "value" : "9" }  
 
{ "_id" : ObjectId("4e3f33e26266b5845052c02e"), "value" : "10" }

The new dbref method is used to complete the set association

//The new dbref keyword is added to complete the association of the set. Here, new dbref is used as the keyword, where a is key and objectid is value
> var Ba={Apid:[new DBRef('A',ObjectId("4e3f33de6266b5845052c02c"))],value:3}                        
 
 //Save collection
> db.B.save(Ba)  
 
> var Ba={Apid:[new DBRef('A',ObjectId("4e3f33de6266b5845052c02c"))],value:4}  
 
> db.B.insert(Ba)                                                              
 
> var Ba={Apid:[new DBRef('A',ObjectId("4e3f33de6266b5845052c02c"))],value:7}  
 
> db.B.insert(Ba)                                                              
 
> var Ba={Apid:[new DBRef('A',ObjectId("4e3f33de6266b5845052c02c"))],value:8}  
 
> db.B.insert(Ba)                                                              
 //Make a query
> db.B.find()  
 
 //As you can see, the association has been successful
{ "_id" : ObjectId("4e3f3dd96266b5845052c035"), "Apid" : [ { "$ref" : "A", "$id" : ObjectId("4e3f33de6266b5845052c02c") } ], "value" : 3 }  
 
{ "_id" : ObjectId("4e3f3de16266b5845052c036"), "Apid" : [ { "$ref" : "A", "$id" : ObjectId("4e3f33de6266b5845052c02c") } ], "value" : 4 }  
 
{ "_id" : ObjectId("4e3f3dec6266b5845052c037"), "Apid" : [ { "$ref" : "A", "$id" : ObjectId("4e3f33de6266b5845052c02c") } ], "value" : 7 }  
 
{ "_id" : ObjectId("4e3f3df06266b5845052c038"), "Apid" : [ { "$ref" : "A", "$id" : ObjectId("4e3f33de6266b5845052c02c") } ], "value" : 8 }

Using Mongo Java mode

//Create a foreign key for association, where the foreign key is refb
            //The DB database is selected to operate and ID is selected as the database association
            DBRef refB = new DBRef(db,"transations", obj.get("_id"));
            //Create a new collection
            DBObject subObj = new BasicDBObject();
            //Foreign key insertion
            subObj.put("brand", refB);
            //Save it
            accounts.save(subObj);

The results of the query are as follows
Understand the basic use of mongodb foreign key
You can see that the value corresponding to $ID is the foreign key of its database mongodb.
This completes the foreign key operation of the database.

official account

Understand the basic use of mongodb foreign key

Recommended Today

Solutions to leetcode problems and knowledge points 1. Sum of two numbers

Title Link 1. Two Sum  difficulty: $/ color {00965e} {easy}$ Knowledge points 1. Hash (hash) function The classic hash function times33 is widely used, and the core algorithm is as follows: hash(i) = hash(i-1) * 33 + str[i] Laruence has an article about:Hash algorithm in PHP 2. Hash collision processing method 2.1 chain address method […]