Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could store everything in a map. The <code>mgo/bson</code> package provides a <code>bson.M</code> data type that can be used to store arbitrary data and since MongoDB doesn't enforce a strong schema, <code>mgo</code> uses the <code>bson.M</code> type internally for everything.</p> <p>If you just want to display the data, using a <code>bson.M</code> should be fine, but once you want to start working with it, you should consider using a struct instead. Otherwise, you would need a lot of type assertions in your program. For example, consider you want to print the title (<code>result["title"]</code>) of your document in upper case. By using just <code>bson.M</code>, your code would look like:</p> <pre><code>// is there a title attribute? if title, ok := result["title"]; ok { // is it a string? (and not another map or integer or something else) if titleStr, ok := title.(string); ok { // ok, it is a string fmt.Println("Title: ", strings.ToUpper(titleStr)) } } </code></pre> <p>Your program would become much more readable and easier to maintain when you let <code>mgo</code> convert the data to a struct for you. Then, the same code might read as:</p> <pre><code>fmt.Println(strings.ToUpper(result.Title)) </code></pre> <p>Normally you define one struct type for each type of document you want to deal with (i.e. one type for "users", another for "blog posts", etc.) that contains every attribute that you might want to access. If your user document does not happen to have an email address assigned, you will just get an empty string (or more generally, the zero value) back when you decode it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload