计算与 Mgo 中的查询匹配的文档

Count Documents That Match a Query in Mgo

我想根据文档中的字段获取集合中的计数。

根据Mongodb documentation,我们可以使用runCommand()来做到这一点。 例如:

db.runCommand( { count:'orders',
                 query: { ord_dt: { $gt: new Date('01/01/2012') } }
               } )

但是我如何在 MGO 中执行此操作?

Mgo 好像没有包含runco​​mmand。我正在使用 mgo.v2。

runCommand()mgo 包中可用 Database.Run(). For an example how to use it, see this answer:

但是你想要的可以简单地通过使用Query.Count()方法来实现:

coll := ... // obtain collection...

count, err := coll.Find(bson.M{"ord_dt": bson.M{
    "$gt": time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC),
}}).Count()