Docs Menu

Specify a Query

On this page

  • Overview
  • Literal Values
  • Comparison
  • Logical
  • Element
  • Evaluation
  • Array
  • Bitwise
  • Additional Information

In this guide, you can learn how to specify a query to match a subset of documents.

To match a subset of documents, specify a query filter containing your match criteria. Match criteria consist of the fields and values you want present in a document. A query filter contains at least one set of match criteria to determine which documents to include in the resulting set.

In a query filter, you can match fields with literal values or with query operators. Query operators allow you to perform mathematical or logical operations to locate documents within a collection.

Match criteria with literal values use the following format:

filter := bson.D{{"<field>", "<value>"}}

Match criteria with a query operator use the following format:

filter := bson.D{{"<field>", bson.D{{"<operator>", "<value>"}}}}

The following sections use literal values and query operators with the Find() function to match a subset of documents.

To run the examples in this guide, load the sample data into the ratings collection of the tea database with the following snippet:

coll := client.Database("tea").Collection("ratings")
docs := []interface{}{
bson.D{{"type", "Masala"}, {"rating", 10}, {"vendor", bson.A{"A", "C"}}},
bson.D{{"type", "English Breakfast"}, {"rating", 6}},
bson.D{{"type", "Oolong"}, {"rating", 7}, {"vendor", bson.A{"C"}}},
bson.D{{"type", "Assam"}, {"rating", 5}},
bson.D{{"type", "Earl Grey"}, {"rating", 8}, {"vendor", bson.A{"A", "B"}}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
Tip
Non-existent Databases and Collections

The server implicitly creates the necessary database and collection when you perform a write operation against them if they don't already exist.

Each document contains a rating for a type of tea and the vendors that carry them, which corresponds to the rating, type, and vendor fields.

Note

Each example truncates the ObjectID value because the driver generates them uniquely.

Literal value query filters return documents with an exact match to your match criteria.

Tip

If you specify an empty query filter, CRUD operations match all the documents in a collection.

The following example matches documents where the type is "Oolong":

filter := bson.D{{"type", "Oolong"}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type Oolong} {rating 7} {vendor [C]}]
Tip

Literal value queries return the same value as the $eq comparison operator. For example, the following query filters produce the same result:

filter := bson.D{{"type", "Oolong"}}
filter := bson.D{{"type", bson.D{{"$eq", "Oolong"}}}}

Comparison operators analyze the value in a document against the specified value in your match criteria. Common comparison operators include $gt for "greater than" comparisons, $lte for "less than or equal to" comparisons, and $ne for "not equal to" comparisons.

The following example matches documents where the rating is less than 7:

filter := bson.D{{"rating", bson.D{{"$lt", 7}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type English Breakfast} {rating 6}]
[{_id ObjectID("...")} {type Assam} {rating 5}]

For a full list of comparison operators, see the Comparison Query Operators page.

Logical operators require at least two match criteria. They check if documents meet all, at lease one, or none of the specified criteria. Common logical operators include $and where all match criteria must be true, and $or where at least one of the match criteria must be true.

The following example matches documents where the rating is greater than 7 and less than or equal to 10:

filter := bson.D{
{"$and",
bson.A{
bson.D{{"rating", bson.D{{"$gt", 7}}}},
bson.D{{"rating", bson.D{{"$lte", 10}}}},
},
},
}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type Masala} {rating 10} {vendor [A C]}]
[{_id ObjectID("...")} {type Earl Grey} {rating 8} {vendor [A B]}]

For a full list of logical operators, see the Logical Query Operators page.

Tip

Multiple match criteria resembling an $eq comparison operator in a literal query return the same value as the $and logical operator. For example, the following query filters produce the same result:

filter := bson.D{{"type", "Oolong"}, {"rating", 7}}
filter := bson.D{
{"$and",
bson.A{
bson.D{{"type", "Oolong"}},
bson.D{{"rating", 7}},
}},
}

Element operators check for the presence or type of the specified field.

The following example matches documents where the vendor field does not exist:

filter := bson.D{{"vendor", bson.D{{"$exists", false}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type English Breakfast} {rating 6}]
[{_id ObjectID("...")} {type Assam} {rating 5}]

For a full list of element operators, see the Element Query Operators page.

Evaluation operators analyze values in a document based on the specified value in your match criteria. Common evaluation operators include $regex where a field's value must match the specified regular expression and $text where the field's value must contain the specified string.

The following example matches documents where the type begins with the letter "E":

filter := bson.D{{"type", bson.D{{"$regex", "^E"}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type English Breakfast} {rating 6}]
[{_id ObjectID("...")} {type Earl Grey} {rating 8} {vendor [A B]}]

For a full list of evaluation operators, see the Evaluation Query Operators page.

Array operators check the values or amount of elements in an array field.

The following example matches documents where the vendor contains "C":

filter := bson.D{{"vendor", bson.D{{"$all", bson.A{"C"}}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type Masala} {rating 10} {vendor [A C]}]
[{_id ObjectID("...")} {type Oolong} {rating 7} {vendor [C]}]

For a full list of array operators, see the Array Query Operators page.

Bitwise operators convert a numeric field from a base-10 (decimal) number into the corresponding base-2 (binary) number. They check whether the value in a document has the same bits set as the value in your match criteria.

The following example matches documents where the rating has the same bits set as 6 (which is "00000110"):

filter := bson.D{{"rating", bson.D{{"$bitsAllSet", 6}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

The expected output of this example is as follows:

[{_id ObjectID("...")} {type English Breakfast} {rating 6}]
[{_id ObjectID("...")} {type Oolong} {rating 7} {vendor [C]}]

For a full list of bitwise operators, see the Bitwise Query Operators page.

For more information on any of the functions or types used in this guide, see the following API Documentation:

Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.