MongoDB 3.x Client Development four: Golang query MongoDB collection data based on conditional filtering

Source: Internet
Author: User
Tags mongodb collection mongodb query
This is a creation in Article, where the information may have evolved or changed.

More Articles


Quick Smart Programmer Community


Front-end input query criteria, background based on query criteria, query MongoDB, filtered results are displayed again.

Front page:

<body>
<a href= "Connect" > Return </a>
<form action= "Query" method= "get" >
Query condition: <input type= "text" name = "Querystr" value= "size=" 60″/>
<input type= "Submit" value= "Query"/>
</form>
<table border= "1″>
{{range $i, $m: =.}}
<tr>
{{range $k, $v: = $m}}
<td>
<div>{{$k}}</div>
</td>
<td>
<div>{{$v}}</div>
</td>
{{End}}
</tr>
{{End}}

</table>
</body>


Golang,erlang,java,groovy discussion, QQ Group: 367583891


Golang Code:

Func query (w http. Responsewriter, r *http. Request)  {r.parseform () collections := r.form["collection"]if len (collections)  >  0 {collection = collections[0]}fmt. Println ("collection:",  collection)//Get query condition string querystrs := r.form["Querystr"]querystr :=   "" If len (querystrs)  > 0 {querystr = querystrs[0]}session, err  := mgo. Dial (URL)  //connection database CheckError (ERR) defer session. Close () session. SetMode (MgO. Monotonic, true) db := session. DB ("Test") coll := db. C (collection)//query condition string converted to MongoDB query JSON object var condition map[string]interface{}var byt =  make ([]byte, 0) if querystr !=  ""  {byt = []byte (QUERYSTR)}json. Unmarshal (byt, &condition)//query iter := coll by condition. Find (condition). Limit (100). Iter (Var rows = make) ([]bson. m, 0) Var row interface{}foR iter. Next (&row)  {fmt. Println (Row. ( Bson. M) ["name"]) Rows = append (Rows, row. ( Bson. M))}t, err := template. Parsefiles ("template/query.html") checkerror (Err) err = t.execute (w, rows) CheckError (ERR)}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.