使用Golang在MongoDB中无循环更新文档

使用Golang在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.

我有一个收集器模块,该模块每30秒提取一次远程API。 这会给我一个对象列表 在MongoDB数据库中插入或更新。 p>

  {
“ id”:“ oulkhhvoiupokb”,
“ name”:“ test1”,
“ status”:“  OPEN“ 
},
 {
” id“:” oulkhhvoisksbsjkkb“,
” name“:” test2“,
” status“:” CLOSED“ 
} 
  code>  pre  > 
 
 

实际上,我只收集具有OPEN状态的对象。 并通过循环将对象的其余部分设置为CLOSED(因为它们未打开)。 但是将来,这会花费很多时间,因为对象的数量会不断增长。 p> \ n

我使用Golang和MGO软件包。 p>

请问有没有一种方法可以使它更快更干净? 像为Mongo文档设置基本字段值之类的东西? p>

要另外解释一下,当我将OPEN对象插入数据库时​​,必须关闭数据库中已经存在的所有其他对象 。 Mongo可以做到吗? p>

谢谢。 p> div>

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.