Last active
March 19, 2020 15:41
-
-
Save mrjazz/cb0f2218ea7f223ddc2808436091ac39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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