使用gopkg.in/mgo.v2在Mongo中检查对象的存在性。

huangapple go评论155阅读模式
英文:

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

问题

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

  1. type result interface{}
  2. var res result
  3. err := col.Find(bson.M{"title": "title1"}).One(&res)
  4. if err != nil {
  5. if err.Error() == "not found" {
  6. log.Println("No such document")
  7. } else {
  8. log.Println("err occured", err)
  9. }
  10. }

我不想创建变量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

  1. type result interface{}
  2. var res result
  3. err := col.Find(bson.M{"title": "title1"}).One(&res)
  4. if err != nil {
  5. if err.Error() == "not found" {
  6. log.Println("No such document")
  7. } else {
  8. log.Println("err occured", err)
  9. }
  10. }

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{字段: 值}).计数()

英文:
  1. 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函数获取具有特定键的文档数量:

  1. 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 :

  1. count, err := collection.CountDocuments(context.TODO(), bson.D{{&quot;key&quot;, &quot;value&quot;}})

huangapple
  • 本文由 发表于 2015年9月27日 15:12:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/32805478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定