Creating own "_id" field in MongoDB collection

3 vues (au cours des 30 derniers jours)
Bálint Décsi
Bálint Décsi le 21 Mai 2019
Commenté : Jason Steiner le 6 Déc 2023
Descripition
How can I create a valid "_id" field in a struct that MongoDB accepts for its default primary key field? I'm having this trouble when trying to insert a structure into a MongoDB database as a collection using the Database Toolbox Interface for MongoDB. Since MongoDB automatically creates a hexadecimal number for "_id" field for each document even if I give it an "ID" field and I don't want the "_id" to be a hexadecimal (I'd like to provide certain numbers from MATLAB) or having both "_id" and "ID" fields, I should have an "_id" field with the desired value in the structure I'm passing on to the interface.
Errors I got
According to the MATLAB documentation, a valid field name should start with a letter, so when running
cellProps = struct('_id', []);
I get the following error:
Error using struct
Invalid field name "_id".
Steps that did not solve my problem
Checking how MATLAB displays the "_id" field in the Command Window querying a MongoDB database (importing records). It resulted "x_id", and when giving this name to the exported structure's field, MongoDB still creates both "_id" (hexadecimal) and my own "x_id".
  2 commentaires
Jeff
Jeff le 5 Avr 2023
I think that's a proprietary ID used only by MongoDb. I'm trying to figure out how to read it, because matlab won't let me address it as "thing._id" ;)
Jason Steiner
Jason Steiner le 6 Déc 2023
Reading it requires a slight workaround, but it is pretty painless. You need to reference that field in paranthesis mode.
id = thing.('_id');
I'm still fighting the original issue from this post; I can't set the _id term in the write, so I can't update a collection that has multiple documents that match the queries needed.

Connectez-vous pour commenter.

Réponses (0)

Produits


Version

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by