简体   繁体   中英

Check object existence in mongo using gopkg.in/mgo.v2

I am looking for convinient way to check if object already exists in collection. For now the only way that i have found is

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)
    }
}

I dont want to create variable res, in case if object exists, it can be very heavy document with a lot of fields. I wish there would be another way, some Check() function which will just return bool value.. Basically I only need to know that object already stored in collection, I dont need itself

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

you have to use $exists

Syntax: { field: { $exists: } }

For more details

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM