databasemongodbgodbrefmongo-go

Using DBRef in mongo go driver


I want to use DBref with go-mongo-driver but I couldn't find any example about it. How can I achieve this? I worked with Spring Data Mongodb before and you can indicate Dbref inside a class like :

@DBRef private EmailAddress emailAddress;

Is there anybody to show up a good example? Thanks in advance


Solution

  • I worked with Spring Data Mongodb before and you can indicate Dbref inside a class

    Unless you have a compelling reason to use DBRefs you should avoid it, or use manual references instead.

    With the example that you posted, you should definitely try to embed the value of EmailAddress in the document first. Using an embedded model should save you from querying the database twice just to retrieve EmailAddress value. See also Embedded Data Models.

    type User struct 
    {
        ID           primitive.ObjectID `json:"ID" bson:"_id"`
        UserName     string             `json:"username"`
        EmailAddress Email              `json:"emailAddress"`
    }
    
    type Email struct 
    {
         PrivateEmail     string      `json:"private"`
         BusinessEmail    string      `json:"business"`
    }
    

    In some cases, where you do need to store related information in separate documents, you should use manual references. You can do this by saving the _id field of one document in another document as a reference. Then your application can run a second query to return the related data. Since MongoDB v3.4+, you can use either $lookup or $graphLookup to perform a lookup.

    MongoDB Go driver does not have direct support for DBRef type. Spring Data MongoDB provides a convenient helper methods that form the query of DBRef automatically, although behind the scene it's just querying the database twice.

    Having said all the above, and there's some special edge case that you need it you can construct your own struct as below example:

    type User struct 
    {
        ID               primitive.ObjectID  `json:"ID" bson:"_id"`
        UserName         string              `json:"username"`
        EmailAddress     DBRef               `json:"emailAddress"`
    }
    
    type DBRef struct {
       Ref interface{}   `bson:"$ref"`
       ID  interface{}   `bson:"$id"`
       DB  interface{}   `bson:"$db"`
    }
    

    Again, please note that MongoDB drivers do not automatically resolve DBRef. There may be frameworks or helpers on top of the driver that could provide the automatic reference resolution (looking up the value by performing a second query).