You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
808 B
33 lines
808 B
5 years ago
|
package database
|
||
6 years ago
|
|
||
|
import (
|
||
5 years ago
|
"fmt"
|
||
|
|
||
5 years ago
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
|
||
5 years ago
|
"github.com/mainnika/mongox-go-driver/v2/mongox/query"
|
||
6 years ago
|
)
|
||
|
|
||
|
// Count function counts documents in the database by query
|
||
|
// target is used only to get collection by tag so it'd be better to use nil ptr here
|
||
5 years ago
|
func (d *Database) Count(target interface{}, filters ...interface{}) (int64, error) {
|
||
6 years ago
|
|
||
5 years ago
|
collection := d.GetCollectionOf(target)
|
||
6 years ago
|
opts := options.Count()
|
||
|
composed := query.Compose(filters...)
|
||
|
|
||
|
opts.Limit = composed.Limiter()
|
||
|
opts.Skip = composed.Skipper()
|
||
|
|
||
5 years ago
|
result, err := collection.CountDocuments(d.Context(), composed.M(), opts)
|
||
6 years ago
|
if err == mongo.ErrNoDocuments {
|
||
5 years ago
|
return 0, err
|
||
6 years ago
|
}
|
||
|
if err != nil {
|
||
5 years ago
|
return 0, fmt.Errorf("can't decode desult: %w", err)
|
||
6 years ago
|
}
|
||
|
|
||
|
return result, nil
|
||
|
}
|