Reputation: 591
I am new to mongodb and I am trying to structure my data utilizing the one-to-many data model. However, the way it’s structure now, I do not think it would work.
I have two collections; sources and articles.
When storing sources, I allowed Mongo to auto-generate the _id field with the objectID. Now as I reference the mongodb one-to-many docs again, I am wondering if I should've of generated the _id with a source name I could reference in the articles
Below is an example of how sources are stored
{
_id:"5cc76a83d6c44rae88e221b7"
id:"abc-news-au"
name:"ABC News AU"
description:"ABC News is a national news service in..." url:"https://www.abc.net.au/news/"
language:"en"
country:"au"
}
Below is an example of how articles are stored
{
_id:"5c93ffbf986d098b27b55c72
title:"'It doesn't get you stoned':
url":"https://www.abc.net.au/news/2019-03-09/medicinal-cannabis-and-ageing/10824750"
description":"A growing number of senior Australians..."
author:"ABC North Coast By Catherine Marciniak"
publishedAt":"2019-03-08T20:00:09.000Z"
content:"Sixty-five-year-old Julie has never smoked a joint in..."
name:"ABC News AU"
urlToImage:"https://www.abc.net.au/news/image/10729312-16x9-700x394.jpg"
summarization:"Sixty-five-year-old Julie has never smoked a joint.."
source:"abc-news-au"
}
With the way the sources and articles are currently structured, is it considered one-to-many data structure? Or will I need to convert the id field in the sources documents to the _id field. For example, changing the objectID to _id: “abc-news-au”
, and the ref id in the articles to sources_id: “abc-news-au”
?
Upvotes: 0
Views: 229
Reputation: 99
The _id field should always be an ObjectId, just as auto-generated. I can see no reason why the structures you have presented wouldn't work in a one to many relationship.
If you wish to populate (JOIN) them, you can perform a $lookup between source name article field and your own id field. See $lookups: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/.
Alternatively you could introduce a sourceId field onto the article, which would reference the source. The advantage of this is, even should the name of the source change, the reference is safe.
Upvotes: 1