使用gopkg.in/ go.v2检查mongo中的对象是否存在



我正在寻找方便的方法来检查对象是否已经存在于集合中。目前我找到的唯一方法是

type result interface{}
var res result
err := col.Find(bson.M{"title": "title1"}).One(&res)
if err != nil {
    if err.Error() == "not found" {
        log.Println("No such document")
    } else {
        log.Println("err occured", err)
    }
}

我不想创建可变的分辨率,如果对象存在,它可能是一个非常重的文档,有很多字段。我希望有另一种方法,一些Check()函数将返回bool值…基本上我只需要知道对象已经存储在集合中,不需要它本身

count, err = collection.Find(bson.M{field: value}).Count()

必须使用$exists

语法:{field: {$exists:}}

查看更多详细信息

http://docs.mongodb.org/manual/reference/operator/query/exists/

在官方Mongo驱动程序中,您可以使用CountDocuments函数获得具有特定键的文档计数:

count, err := collection.CountDocuments(context.TODO(), bson.D{{"key", "value"}})

最新更新