Inserting new sub-document ObjectId's

Early development, I have a collection with the following document structure:

Of note is comp.id

The “Ernie Els” document was entered manually via the Atlas web UI. It has an actual ObjectId for the comp sub-document.

When I use my PHP site to enter new records (still under development, obviously…), the format appears as a String, which is the 2nd document with my playerName.

The insert syntax currently is:

$insertOneResult = $collection->insertOne(
  [
    'playerName' => $_SESSION['playerName'],
    ...
    'comp' => [
      'id' => $_SESSION['compId'],
      ...
    ]
  ]
);

What do I need to change, please?

1 Like

Hi Dan,

I would try:
'id' => ObjectId($_SESSION['compId']),
or
'id' => new MongoId($_SESSION['compId']) /* this might throw an Exception if compId is not a valid reference syntax */

That code was untested however as I only started learning MongoDB and am thinking of changing implementation in my application.

HTH,
Stay safe.

1 Like

Thanks @MaxOfLondon, I used the latter code:

'id' => new MongoDB\BSON\ObjectID($_SESSION['compId'])

compId must exist at the time of saving this new document, otherwise I have other problems in any case!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.