Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
MongoDB's query language is built around composable operator objects. Understanding the operator taxonomy — comparison (ne, lt, nin), logical (or, exists, regex operator deserves special attention because unanchored regex patterns always do a full collection scan regardless of indexes.
Query a products collection using comparison, logical, and regex operators.
$nin. Verify the count matches documents outside those exact prices.inStock: false to the Doohickey. Query { inStock: { $ne: true } } — confirm it returns both documents missing the field AND the one explicitly set to false. Explain why.name. Run { name: /widget/i } (unanchored) and { name: /^Widget/ } (anchored) through explain('executionStats'). Note which uses the index and which does a COLLSCAN.Use these three in order. Each builds on the one before.
List MongoDB's comparison query operators ($eq, $ne, $gt, $gte, $lt, $lte, $in, $nin) and give a one-line use case for each.
Explain how MongoDB evaluates a compound filter like `{ tags: { $in: [...] }, price: { $gt: 5 } }`. Does it short-circuit? In what order are conditions checked relative to index usage?
I need to query documents where an embedded array field contains at least two specific values simultaneously — e.g. tags contains both 'sale' AND 'new'. What operator do I use and how does MongoDB evaluate it?
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 main() {
client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
col := client.Database("demo").Collection("products")
// Seed
col.InsertMany(context.TODO(), []interface{}{
bson.D{{"name", "Widget Pro"}, {"price", 49.99}, {"tags", bson.A{"sale", "new"}}},
bson.D{{"name", "Gadget"}, {"price", 99.00}, {"tags", bson.A{"new"}}},
bson.D{{"name", "Doohickey"}, {"price", 9.99}, {"tags", bson.A{"clearance"}}},
})
// $in + $gt
filter := bson.D{
{"tags", bson.D{{"$in", bson.A{"sale", "clearance"}}}},
{"price", bson.D{{"$gt", 5.0}}},
}
cursor, _ := col.Find(context.TODO(), filter)
var results []bson.M
cursor.All(context.TODO(), &results)
for _, r := range results { fmt.Println(r["name"], r["price"]) }
}go run main.go