Creating own "_id" field in MongoDB collection

조회 수: 6 (최근 30일)
Bálint Décsi
Bálint Décsi 2019년 5월 21일
댓글: Jason Steiner 2023년 12월 6일
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
Jeff
Jeff 2023년 4월 5일
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 2023년 12월 6일
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.

댓글을 달려면 로그인하십시오.

답변 (0개)

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by