Skip to content

Instantly share code, notes, and snippets.

@mrjazz
Last active March 19, 2020 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrjazz/cb0f2218ea7f223ddc2808436091ac39 to your computer and use it in GitHub Desktop.
Save mrjazz/cb0f2218ea7f223ddc2808436091ac39 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func findAllValues() chan bson.M {
connStr := "mongodb://localhost:27018"
var mongoClient, _ = mongo.Connect(context.TODO(), options.Client().ApplyURI(connStr))
items := mongoClient.Database("example").Collection("values")
cursor, _ := items.Find(context.TODO(), bson.M{})
channel := make(chan bson.M)
go func() {
for cursor.Next(context.TODO()) {
var value bson.M
cursor.Decode(&value)
value = bson.M{"value": "ok"}
channel <- value
}
close(channel)
}()
return channel
}
func main() {
chnlWithRecords := findAllValues()
for i := range chnlWithRecords {
fmt.Println(i)
}
}
// Output is correct because we get only map[value:ok] in output
go run works-well.go
map[value:ok]
map[value:ok]
map[value:ok]
map[value:ok]
map[value:ok]
map[value:ok]
map[value:ok]
map[value:ok]
map[value:ok]
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment