I have a JSON I would like to put into my mongo db database. My JSON holds some relational data. This data is internal to that JSON, I don't need to store this anywhere else. Example:
{
title: "John film list"
films [
{
title: "Once upon a time in Hollywood"
director: '1a' //referencing the director using an ID of type string
},
{
title: "Some film with empty director field",
director: ''
}
],
directors: [
{
id: '1a', //find the director here
name: 'Tarantino'
}
]
}
I do not need to store anything centrally (I don't need a big list of directors somewhere), but in this very document I need to be able to look up the director (1a
) and get back Tarantino.
I managed to push this JSON format to MongoDB. However, it gives my schemas new ids (_id
-field) and I am confused now as to how to relate the two properly in mongo?
The default unique primary key in the MongoDB document is _id. When you insert a new document, it returns the unique id of the record that inserted (created).
The value inside this id is ObjectId who creates based on time. you can read about it here.
If you want to use your own value for the _id, have to pass it when you call the insert, like this:
db.directors.insertOne({_id: '1a', name: 'Tarantino'})