将带有内部关系数据的 JSON 推送到 MongoDB?
Pushing JSON with internal relational data to MongoDB?
我有一个 JSON 我想放入我的 mongo 数据库。我的 JSON 保存一些关系数据。此数据是 JSON 的内部数据,我不需要将其存储在其他任何地方。示例:
{
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'
}
]
}
我不需要集中存储任何东西(我不需要在某处列出一大堆董事),但在这个文档中我需要能够查找董事 (1a
) 和回到塔伦蒂诺。
我设法将这种 JSON 格式推到 MongoDB。但是,它为我的模式提供了新的 ID(_id
-字段),我现在很困惑如何在 mongo?
中正确关联两者
MongoDB 文档中的默认唯一主键是 _id。当您插入新文档时,它 returns 插入(创建)记录的唯一 ID。
这个id里面的值是根据时间创建的ObjectId。你可以阅读它 here.
如果你想为 _id 使用你自己的值,必须在调用插入时传递它,如下所示:
db.directors.insertOne({_id: '1a', name: 'Tarantino'})
我有一个 JSON 我想放入我的 mongo 数据库。我的 JSON 保存一些关系数据。此数据是 JSON 的内部数据,我不需要将其存储在其他任何地方。示例:
{
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'
}
]
}
我不需要集中存储任何东西(我不需要在某处列出一大堆董事),但在这个文档中我需要能够查找董事 (1a
) 和回到塔伦蒂诺。
我设法将这种 JSON 格式推到 MongoDB。但是,它为我的模式提供了新的 ID(_id
-字段),我现在很困惑如何在 mongo?
MongoDB 文档中的默认唯一主键是 _id。当您插入新文档时,它 returns 插入(创建)记录的唯一 ID。
这个id里面的值是根据时间创建的ObjectId。你可以阅读它 here.
如果你想为 _id 使用你自己的值,必须在调用插入时传递它,如下所示:
db.directors.insertOne({_id: '1a', name: 'Tarantino'})