Skip to content

Instantly share code, notes, and snippets.

@jfjensen
Last active April 7, 2022 15:35
Show Gist options
  • Save jfjensen/b4e5f61c5549d60815fe9eb425a0e379 to your computer and use it in GitHub Desktop.
Save jfjensen/b4e5f61c5549d60815fe9eb425a0e379 to your computer and use it in GitHub Desktop.
This piece of code will query a MongoDB database collection
c := exampleCollection.FindOne(ctx, bson.M{"_id": r.InsertedID})
var exampleResult bson.M
c.Decode(&exampleResult)
fmt.Printf("\nItem with ID: %v contains the following:\n", exampleResult["_id"])
fmt.Println("someString:", exampleResult["someString"])
fmt.Println("someInteger:", exampleResult["someInteger"])
fmt.Println("someStringSlice:", exampleResult["someStringSlice"])
filter := bson.D{{"someInteger", bson.D{{"$lt", 60}}}}
examplesGT50, err := exampleCollection.Find(ctx, filter)
if err != nil {
panic(err)
}
var examplesResult []bson.M
if err = examplesGT50.All(ctx, &examplesResult); err != nil {
panic(err)
}
for _, e := range examplesResult {
fmt.Printf("\nItem with ID: %v contains the following:\n", e["_id"])
fmt.Println("someString:", e["someString"])
fmt.Println("someInteger:", e["someInteger"])
fmt.Println("someStringSlice:", e["someStringSlice"])
}
time.Sleep(20 * time.Second)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment