在Golang中无需循环更新MongoDB文档

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

Update documents without loop in MongoDB with Golang

问题

我有一个收集器模块,每30秒从远程API获取数据。这给我提供了一个对象列表,我将其插入或更新到MongoDB数据库中。

{
"id" : "oulkhhvoiupokb",
"name" : "test1",
"status" : "OPEN"
},
{
"id" : "oulkhhvoisksbsjkkb",
"name" : "test2",
"status" : "CLOSED"
}

实际上,我只收集具有"OPEN"状态的对象。然后通过循环,将其余的对象设置为"CLOSED"(因为它们不是"OPEN")。
但是在将来,由于对象的数量将增加,这将需要很长时间。

我使用Golang和MGO包进行开发。

有没有一种更快、更简洁的方法呢?类似于为Mongo文档设置基本字段值的方式?

换句话说,当我将"OPEN"对象插入数据库时,已经存在于数据库中的所有其他对象必须被设置为"CLOSED"。MongoDB能做到吗?

谢谢。

英文:

I have a collector module that pulls a remote API every 30 seconds.
That gives me a list of objects that I insert or update in a MongoDB database.

{
   "id" : "oulkhhvoiupokb",
   "name" : "test1",
   "status" : "OPEN"
},
{
   "id" : "oulkhhvoisksbsjkkb",
   "name" : "test2",
   "status" : "CLOSED"
}

In fact, I only collect the objects that have the OPEN status. And with a loop, I set the rest of the object as CLOSED (because they are not OPEN).
But in the future, it will take a lot of time because the amont of object will grow.

I work with Golang and MGO package.

Is there a way to do it faster and cleaner please ? Something like setting a basic field value for Mongo documents ?

To explain it differently, when I will insert the OPEN objects in the database, all the other ones that are already in database must be CLOSED. Can Mongo do it ?

Thanks.

答案1

得分: 0

解决方案是使用func (c *Collection) UpdateAll(selector interface{}, update interface{}) (info *ChangeInfo, err error),其中选择器使用$nin,更新部分使用$set

英文:

Solution was to use func (c *Collection) UpdateAll(selector interface{}, update interface{}) (info *ChangeInfo, err error) with the $nin for the selector and $set for the update.

huangapple
  • 本文由 发表于 2017年8月28日 19:19:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/45917769.html
匿名

发表评论

匿名网友

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

确定