gpt4 book ai didi

java - 从 JSON 字符串中提取 ObjectId

转载 作者:行者123 更新时间:2023-11-29 09:30:06 24 4
gpt4 key购买 nike

如何在将 JSON 字符串插入 MongoDB 之前提取其对象 ID?
另外如何设置Object id为主键?

最佳答案

首先MongoDB会自己生成ObjectID("507f191e810c1972xxxxx")(如果你不设置的话)。如 docs 中所述:

All MongoDB documents must have an _id field with a unique value. These operations do not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for the field before inserting it into the collection.

在这篇文章中ObjectID描述了 BSON ObjectID 规范。格式包括:

  1. TimeStamp. This is a unix style timestamp. It is a signed int representing the number of seconds before or after January 1st 1970 (UTC).
  2. Machine. This is the first three bytes of the (md5) hash of the machine host name, or of the mac/network address, or the virtual machine id.
  3. Pid. This is 2 bytes of the process id (or thread id) of the process generating the object id.
  4. Increment. This is an ever incrementing value, or a random number if a counter can't be used in the language/runtime.

The server itself and almost all drivers use the format above.

成功插入后,大多数驱动程序返回包含 ObjectID("507f191e810c1972xxxxx")_id


主键和索引: _id 字段在 MongoDB 中为主键保留,应该是唯一值。如果您没有为 _id 设置任何内容,它将自动生成 ObjectID("507f191e810c1972xxxxx") 如上所述。

MongoDB 创建默认的_id 索引,它是_id 字段上的唯一索引。 MongoDB 默认在所有集合上创建这个索引。您不能删除 _id 上的索引。欲了解更多信息,请访问 link

关于java - 从 JSON 字符串中提取 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21373988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com