MongoDB Compass does not allow ObjectId() while populating DB with "Insert Document" feature?
Asked Answered
B

1

5

I am using MongoDB Compass version 1.25.0.

I was trying to insert a document shared by one of my colleague using the "Insert Document" feature of the MongoDB Compass.

But, it's showing that the document is not in correct format. enter image description here

I think it is validating JSON format and ObjectId() is not a valid JSON value.

I am aware that Compass would create ObjectId() automatically but I want to pass it explicitly.

I resorted to the Shell and I was able to insert the document.

My question is does MongoDB Compass allow entering ObjectId() from the UI? If yes, what am I doing wrong?

Byebye answered 11/2, 2021 at 5:32 Comment(7)
"asdf" as seen in the image is not a valid value. ObjectId constructor takes a hexadecimal value of the format shown in the docs: ObjectId.Uncork
My bad it was just an example. Updated the question.Byebye
The document view is of JSON format. You need to use Extended JSON format for the ObjectId.Uncork
When using the format you suggested {"$oid":"5d505646cf6d4fe581014ab2"} it shows BSON field 'insert.documents.0' is the wrong type 'objectId', expected type 'object'Byebye
See the documentation for Compass - Insert.Uncork
Already went through it. it says if not provided "_id" will be inserted automatically. It does not say how to insert ObjectId.Byebye
@Uncork I was able to solve it. It was just a matter of syntax. Thanks.Byebye
B
8

I was able to insert a document with ObjectId using below syntax:

{
    "_id": {
        "$oid": "60261ccf416a1ed478d7357a"
    }
}

I found that the documentation of a bit off in clarifying how the $oid is supposed to be used. At least for someone beginner like me.

enter image description here

Byebye answered 12/2, 2021 at 6:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.