Finder
The Finder() method is used to obtain a new generic query object, namely Finder[T]. With the methods of Finder[T], we can execute relevant query operations.
Find a single document
user, err := userColl.Finder().Filter(query.Id("60e96214a21b1b0001c3d69e")).FindOne(context.Background())The
FindOnemethod is used to query a single document.useris a pointer object of the specified generic type, i.e.,*User.The
Filtermethod allows us to specify search criteria. It accepts parameters of typeany, meaning any type of argument can be passed in, provided they are valid query conditions. In the example above,query.Id("60e96214a21b1b0001c3d69e")is used to specify the search condition where_idequals60e96214a21b1b0001c3d69e. For more on building query conditions, refer to thequerypackage.
Find multiple documents
users, err := userColl.Finder().Filter(query.In("_id", "60e96214a21b1b0001c3d69e", "80e96214a21b1b0001c3d70e")).Find(context.Background())- The
Findmethod is used to query multiple documents.usersis a slice of pointer objects of the specified generic type, i.e.,[]*User.
Count document
count, err := userColl.Finder().
Filter(query.NewBuilder().Gt("age", 18).Lt("age", 24).Build()).
Count(context.Background())- The
Countmethod is used to count the number of documents.countis of typeint64.
Distinct query
// v1
//result, err := userColl.Finder().Distinct(context.Background(), "age")
//
//// you can parse the result to slices using the DistinctWithParse method
//ageSlice := make([]int, 0)
//err := userColl.Finder().DistinctWithParse(context.Background(), "age", &ageSlice)
// v2
distinctResult := userColl.Finder().Distinct(context.Background(), "age")
if distinctResult.Err() != nil {
panic(distinctResult.Err())
}
// you can parse the result to slices using the DistinctWithParse method
ageSlice := make([]int, 0)
err := userColl.Finder().DistinctWithParse(context.Background(), "age", &ageSlice)The
Distinctmethod is used to query the unique value of a specified field.mongo-driver v1returns a result of type[]any, whereasmongo-driver v2returns a*mongo.DistinctResult.If you wish to parse the result into a slice, you can use the
DistinctWithParsemethod. This method takes a pointer to a slice as a parameter for parsing the results.