如何为MongoDB中的嵌入式文档创建唯一的ID? [英] How can I create unique IDs for embedded documents in MongoDB?

查看:143
本文介绍了如何为MongoDB中的嵌入式文档创建唯一的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我需要从集合中的项目中唯一引用特定的子文档.例如:

So I need to reference particular subdocuments uniquely from items in my collection. For instance:

User = {
    'name': 'jim',
    'documents: [
        {'id': 0001, 'title': "My document"},
        {'id': 0002, 'title': "My second document!"},
    ]
}

因此,我需要能够为新文档自动创建ID,最好不要在应用程序级别创建ID(因为在实际的开发场景中会出现竞争条件).

So I need to be able to auto-create IDs for new documents, preferably not at the application level (since there will be race conditions in the actual development scenario).

是否可以使用mongo的自动生成的ObjectId(在集合级别的_id字段中使用)或类似的方法?

Is there a way to use mongo's autogenerated ObjectId (used in the _id field at the collection level), or something similar?

推荐答案

是的,使用mongo的ObjectId是可行的方法.唯一的事情是:您必须在应用程序代码中自行生成它们.它们在全球范围内是唯一的,不同的工作人员不会生成两个相同的ObjectId,因此就此而言,没有竞争条件.

Yes, using mongo's ObjectId is the way to go. The only thing is: you have to generate them yourself, in the application code. They are meant to be globally unique, different workers won't generate two identical ObjectIds, so there's no race condition in that sense.

所有官方驱动程序都应提供一种生成ObjectId的方法.这是Ruby中的样子:

All official drivers should provide a way to generate ObjectId. Here's how it is in Ruby:

oid = BSON::ObjectId.new

这篇关于如何为MongoDB中的嵌入式文档创建唯一的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆