-
Type: Task
-
Resolution: Unresolved
-
Priority: Unknown
-
Affects Version/s: None
-
Component/s: CRUD
There are a number of CRUD APIs that accept a filter parameter, including:
Find FindOne FindOneAndUpdate FindOneAndReplace FindOneAndDelete UpdateOne UpdateMany ReplaceOne Distinct DeleteOne DeleteMany
Currently, most users define filters using bson.M or bson.D, which resembles the API used by mongosh. However, the syntax of bson.D can be extremely awkward (see GODRIVER-2271) and defining filters with bson.M requires users to know the proper filter structure and is subject to common field name typos (e.g. "_id").
A much better way to define filters would be using query filter helpers that inform users what filters are available and enforce the correct structure and field naming.
Proposed syntax
Example of finding user documents by name and age
users.Find(ctx, bson.M{"name": "Bob", "age": bson.M{"$gte", 18}})
would become
users.Find(ctx, filter.Eq("name", "Bob").GTE("age", 18))
Example of replacing a document using the default primary ID
coll.ReplaceOne(ctx, bson.M{"_id": id}, doc)
would become
coll.ReplaceOne(ctx, filter.ID(id), doc)
Example of updating a document by the primary ID (using the UpdateByID helper)
coll.UpdateByID(ctx, id, doc)
would become
coll.UpdateOne(ctx, filter.ID(id), doc)
Definition of done
- Create a helper package/type that defines a set of the most commonly used query operators.
- Consider using the Java driver filter builder as reference.
- The helper must be able to be combined with other query filters defined as bson.D or bson.M (i.e. allow incrementally replacing query filters defined with bson.D/bson.M with helper calls without replacing the entire filter).
- Update all documentation to use the filter helpers instead of bson.D/bson.M where possible.
Open questions:
- Should the filter helper be a new package (e.g. filter.Eq), a builder type (e.g. mongo.Filter().Eq), or something else?
- What query operators should we support (see a full list here)?
- Should we only support comparison operators, or other operator types as well (e.g. logical operators, nested element operators, etc)?
- Should the helper output bson.D or another type? It must be possible to mix helper output with other query filters defined using bson.D/bson.M.
- How do we advertise the existence of the filter package, specifically as a replacement for using bson.M or bson.D to define filters?
- is depended on by
-
GODRIVER-3006 Deprecate Collection.UpdateByID
- Blocked
- is related to
-
GODRIVER-2459 Proposal: Improve a way of making filters and aggregation pipilines
- Backlog
-
GODRIVER-2999 Implemente ReplaceByID
- Closed
-
GODRIVER-2889 Create aggregation pipeline helpers
- Backlog
-
GODRIVER-3280 Add Find/Update/Delete by _id helpers
- Closed