Skip to content

Commit bd62d93

Browse files
Cedricdomodwyer
Cedric
authored andcommitted
Add Collation support for calling Count() on a Query (#166)
1 parent 2e9fa92 commit bd62d93

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

session.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4564,10 +4564,11 @@ func (iter *Iter) getMoreCmd() *queryOp {
45644564
type countCmd struct {
45654565
Count string
45664566
Query interface{}
4567-
Limit int32 `bson:",omitempty"`
4568-
Skip int32 `bson:",omitempty"`
4569-
Hint bson.D `bson:"hint,omitempty"`
4570-
MaxTimeMS int `bson:"maxTimeMS,omitempty"`
4567+
Limit int32 `bson:",omitempty"`
4568+
Skip int32 `bson:",omitempty"`
4569+
Hint bson.D `bson:"hint,omitempty"`
4570+
MaxTimeMS int `bson:"maxTimeMS,omitempty"`
4571+
Collation *Collation `bson:"collation,omitempty"`
45714572
}
45724573

45734574
// Count returns the total number of documents in the result set.
@@ -4593,7 +4594,7 @@ func (q *Query) Count() (n int, err error) {
45934594
// simply want a Zero bson.D
45944595
hint, _ := q.op.options.Hint.(bson.D)
45954596
result := struct{ N int }{}
4596-
err = session.DB(dbname).Run(countCmd{cname, query, limit, op.skip, hint, op.options.MaxTimeMS}, &result)
4597+
err = session.DB(dbname).Run(countCmd{cname, query, limit, op.skip, hint, op.options.MaxTimeMS, op.options.Collation}, &result)
45974598

45984599
return result.N, err
45994600
}

session_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1560,6 +1560,38 @@ func (s *S) TestCountQuery(c *C) {
15601560
c.Assert(n, Equals, 2)
15611561
}
15621562

1563+
func (s *S) TestCountQueryWithCollation(c *C) {
1564+
if !s.versionAtLeast(3, 4) {
1565+
c.Skip("depends on mongodb 3.4+")
1566+
}
1567+
session, err := mgo.Dial("localhost:40001")
1568+
c.Assert(err, IsNil)
1569+
defer session.Close()
1570+
1571+
coll := session.DB("mydb").C("mycoll")
1572+
c.Assert(err, IsNil)
1573+
1574+
collation := &mgo.Collation{
1575+
Locale: "en",
1576+
Strength: 2,
1577+
}
1578+
err = coll.EnsureIndex(mgo.Index{
1579+
Key: []string{"n"},
1580+
Collation: collation,
1581+
})
1582+
c.Assert(err, IsNil)
1583+
1584+
ns := []string{"hello", "Hello", "hEllO"}
1585+
for _, n := range ns {
1586+
err := coll.Insert(M{"n": n})
1587+
c.Assert(err, IsNil)
1588+
}
1589+
1590+
n, err := coll.Find(M{"n": "hello"}).Collation(collation).Count()
1591+
c.Assert(err, IsNil)
1592+
c.Assert(n, Equals, 3)
1593+
}
1594+
15631595
func (s *S) TestCountQuerySorted(c *C) {
15641596
session, err := mgo.Dial("localhost:40001")
15651597
c.Assert(err, IsNil)

0 commit comments

Comments
 (0)