英文:
Check object existence in mongo using gopkg.in/mgo.v2
问题
我正在寻找一种方便的方法来检查对象是否已经存在于集合中。目前我找到的唯一方法是:
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)
}
}
我不想创建变量res
,因为如果对象存在,它可能是一个非常庞大的文档,包含许多字段。我希望有另一种方式,一个Check()
函数,它只返回一个布尔值... 基本上,我只需要知道对象是否已经存储在集合中,我不需要对象本身。
英文:
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
答案1
得分: 11
count, err = collection.Find(bson.M{field: value}).Count()的翻译结果是:计数,错误 = 集合.查找(bson.M{字段: 值}).计数()
英文:
count, err = collection.Find(bson.M{field: value}).Count()
答案2
得分: 6
你必须使用 $exists
语法:{ field: { $exists:
更多详细信息请参考:
http://docs.mongodb.org/manual/reference/operator/query/exists/
英文:
you have to use $exists
Syntax: { field: { $exists: <boolean> } }
For more details
http://docs.mongodb.org/manual/reference/operator/query/exists/
答案3
得分: 1
在官方的Mongo驱动程序中,你可以使用CountDocuments函数获取具有特定键的文档数量:
count, err := collection.CountDocuments(context.TODO(), bson.D{{"key", "value"}})
英文:
in the Official Mongo Driver you can get count of documents with specific key using CountDocuments function :
count, err := collection.CountDocuments(context.TODO(), bson.D{{"key", "value"}})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论