加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 服务器 > 系统 > 正文

在MongoDB中的主键是怎样的,怎样自定义主键

发布时间:2023-08-29 15:12:29 所属栏目:系统 来源:
导读:这篇文章给大家分享的是MongoDB中的主键是怎样的,怎样自定义主键。小编觉得挺实用的,因此分享给大家做个参考,文中的介绍得很详细,而要易于理解和学习,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。
这篇文章给大家分享的是MongoDB中的主键是怎样的,怎样自定义主键。小编觉得挺实用的,因此分享给大家做个参考,文中的介绍得很详细,而要易于理解和学习,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。

mongodb中有主键,但是如果不对主键进行设置的话是默认主键。
 
1、默认主键
 
ObjectId 类似唯一主键,可以很快的去生成和排序,包含 12 bytes,含义是:
 
前 4 个字节表示创建 unix 时间戳,格林尼治时间 UTC 时间,比北京时间晚了 8 个小时
 
接下来的 3 个字节是机器标识码
 
紧接的两个字节由进程 id 组成 PID
 
最后三个字节是随机数
 
 
 
MongoDB 中存储的文档必须有一个 _id 键。这个键的值可以是任何类型的,默认是个 ObjectId 对象
 
由于 ObjectId 中保存了创建的时间戳,所以你不需要为你的文档保存时间戳字段,你可以通过 getTimestamp 函数来获取文档的创建时间:
 
通过注释【@Id】设置主键,如果不设置主键,mongoDB会自动生成主键。
 
@Document
 
@Data
 
public class InvoicesMsg {
 
    private String customerId;
 
    private String orderId;
 
    private String money;
 
    private String time;
 
    private String qmz;
 
    public InvoicesMsg(String customerId, String orderId, String money, String time, String qmz) {
 
        this.customerId = customerId;
 
        this.orderId = orderId;
 
        this.money = money;
 
        this.time = time;
 
        this.qmz = qmz;
 
    }
 
}
 
默认生成的数据
 
{
 
    "_id": ObjectId("5cb7d0b95de26915c1433160"),
 
    "customerId": "5c73830e54bbb01d1051ef7d",
 
    "orderId": "0000000120190418090814000001",
 
    "money": "550",
 
    "time": "1555549694",
 
    "qmz": "a1fbbb8fc0d0f2d93c218efc2cd2de517156e30f",
 
    "date": "2019-04-18 09:19:53.396",
 
    "_class": "com.example.btest.demo.bean.InvoicesMsg"
 
}
 
2、自定义主键
 
    @Document
 
@Data
 
public class InvoicesMsg {
 
    public String id; //主键
 
    private String customerId;
 
    private String orderId;
 
    private String money;
 
    private String time;
 
    private String qmz;
 
    public InvoicesMsg(String customerId, String orderId, String money, String time, String qmz) {
 
        this.customerId = customerId;
 
        this.orderId = orderId;
 
        this.money = money;
 
        this.time = time;
 
        this.qmz = qmz;
 
    }
 
}
 
新增一条数据,给id设置值 "1122357" 作为主键
 
{
 
    "_id": "1122357",
 
    "customerId": "00",
 
    "orderId": "1122357",
 
    "money": "10",
 
    "time": "1878678818",
 
    "qmz": "67d53fdccdf29a0686f3e351fe09d61340ea2c85",
 
    "date": "2019-04-19 11:25:29.253",
 
    "_class": "com.example.btest.demo.pojo.InvoicesMsg"
 
}
 
可以看到,主键值设为了 1122357 ,但是字段仍然是_id 。
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章