donglu1971
2016-06-29 01:07
浏览 558

插入MongoDB并存储ObjectID?

So I have a problem, and a few leads on how to fix it. I need help figuring out which one will actually work, and how to execute it.

I'm programming in GoLang and using the mgo package to interact with MongoDB. At a basic level, I need to insert an entry into a collection in Mongo and also have access to that entry's ObjectID.

My first solution would be to search for the entry that matches all the data that I just inserted, but there may be duplicates. I need the EXACT entry.

Second, I would make a field in each entry that's unique, but I don't want useless data in there and I'm also running this concurrently, which can cause problems if I'm trying to make things unique yadda yadda.

Third, there's a NewObjectID() function in mgo, but I don't know how to ensure that it's a Unique ID.

Is there potential in any of these leads or how else can I tackle this?

图片转代码服务由CSDN问答提供 功能建议

所以我有一个问题,还有一些解决方法。 我需要帮助弄清楚哪一个将真正起作用,以及如何执行它。

我正在GoLang中编程,并使用 mgo 包与MongoDB进行交互 。 在基本级别上,我需要将一个条目插入Mongo中的集合中,并且还可以访问该条目的ObjectID。

我的第一个解决方案是搜索与所有 我刚刚插入的数据,但可能有重复项。 我需要EXACT条目。

第二,我将在每个条目中创建一个唯一的字段,但我不想在其中使用无用的数据,而且我还要同时运行它

第三,在 mgo 中有一个 NewObjectID()函数会导致问题 ,但我不知道如何确保它是唯一ID。

这些潜在客户中是否有潜力,或者我还能如何解决? < / DIV>

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douaoj0994 2016-06-29 02:23
    已采纳

    Create an id with NewObjectId. The bson package ensures that the id is unique.

    id := bson.NewObjectId()
    

    Set the id in the document before inserting it. Store the field with the name "_id".

    struct MyDoc {
       ID bson.ObjectId `bson:"_id"`
       // other fields
    }
    
    d := &MyDoc{ID: bson.NewObjectId(), /* set other fields */ }
    
    if err := c.Insert(d); err != nil {
        // handle error
    }
    

    The inserted document has the identifier id.

    打赏 评论

相关推荐 更多相似问题