Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

go

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

like image 940
Kaign Avatar asked Sep 27 '15 07:09

Kaign


2 Answers

count, err = collection.Find(bson.M{field: value}).Count()
like image 153
Activecat Avatar answered Oct 22 '22 22:10

Activecat


you have to use $exists

Syntax: { field: { $exists: } }

For more details

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

like image 36
Rohit Jain Avatar answered Oct 22 '22 22:10

Rohit Jain