mongoDB ObjectID

3369 ワード

ObjectIDとは?

  • ObjectIDはモンデ比のデータ型の一つであり、主にPKのデータ型に用いられる
  • MongoDeviのすべての添付ファイルには_idフィールドがあります.idは任意のタイプであってもよいが、集合内で一意でなければならない.
  • _idのデフォルトタイプはObjectIDタイプであり、開発者がObjectIDを入力していない場合はMongoDBドライバによって作成されます.
  • rdbがpkとしてauto incrementキーを使用しないのは、分散環境でモンゴディビが使用しているためである.(シャーディン環境の一意の識別子)
  • ObjectIDは、上図のように12バイトであり、時間+ランダム値+countの組み合わせである.
  • countも値を作成しました
  • ObjectIDを含むオブジェクトの作成

    type OjbectIDTestStruct struct {
    	ID    primitive.ObjectID `bson:"_id,omitempty"`
    	Name string
    }
  • id、省略記号も必要です.
  • notifemptyが存在しない場合、ローカル初期化のidに入ります.(ディビでxを作成します)
  • 作成時にObjectIDは更新されません。

    testStruct := OjbectIDTestStruct{Name: "test1"} 
    // testSturct.ID = []uint{0,0,0,0,0,0,0,0}
    
    collection.InsertOne(ctx, &testStruct)
    // testSturct.ID = []uint{0,0,0,0,0,0,0,0}

    結果からObjectIDを選択して更新できます。

    testStruct := OjbectIDTestStruct{Name: "test1"} 
    // testSturct.ID = []uint{0,0,0,0,0,0,0,0}
    
    result, err := collection.InsertOne(ctx, &testStruct)
    
    testStruct.ID = result.InsertedID 
    // testStruct.ID = []uint{97,206,146,190,8,...}

    created atをポップアップ

    myStruct.ID.Timestamp

    (概ね)create atの順序と似ている。

  • なぜ「粗い」と呼ぶのか
    While ObjectId values should increase over time, they are not necessarily monotonic. This is because they:
    Only contain one second of temporal resolution, so ObjectId values created within the same second do not have a guaranteed ordering, and Are generated by clients, which may have differing system clocks.
  • は秒単位でしか記憶されていないため、nanosecond単位に達する保証はありません.
  • 秒に一致すると、どの値が先に入力されたのか分かりません.
  • Are generated by clients, which may have differing system clocks. → ? どういう意味かわかりませんが