F
F
FedorWK2022-02-05 18:51:55
MongoDB
FedorWK, 2022-02-05 18:51:55

How to correctly insert an object with an ObjectID field into MongoDB (Golang mongo-driver)?

There is a structure with a primitive.ObjectID field, which must be assigned by the DBMS itself.

type Indicator struct {
  Id          primitive.ObjectID `bson:"_id"`
  Name        string
  Ticker      string
  Options     map[string]interface{}
  Subscribers []string
}

That is, when creating a structure, I fill in all the fields except for the ID. Next, using collection.InsertOne() I add the structure to the database, where it is assigned an empty "_id". Accordingly, the InsertedID returned by InserOne() is also empty.

How do I get Mongo to automatically assign the correct ObjectID to a document?

Test code:

testIndicator := db.Indicator{
    Name:   "testLevel",
    Ticker: "AAPL",
    Options: map[string]interface{}{
      "price":       238.0,
      "update_rate": "30min",
    },
    Subscribers: []string{"testsub1", "testsub2"},
  }

  res, err := indicatorCollection.InsertOne(ctx, testIndicator)
  if err != nil {
    t.Error(err)
  }
  fmt.Println(res.InsertedID) // выводит: ObjectID("000000000000000000000000")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WinPooh32, 2022-02-08
@FedorWK

That's right, you send such an _id when sending, because you have this value in the structure by default.
There are several options for resolving the issue:
1) Use different structures for receiving and sending, where there will be no _id field in the structure for insertion, then the monga itself will set the value for id.
2) Or generate id on the client through primitive. NewObjectID ()
in your case:

testIndicator := db.Indicator{
    ID: primitive.NewObjectID(),
    ...
  }

3) Use *primitive.ObjectID as the type for the ID, nil will be the default value, then monga will create the object itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question