I am currently investigating the best way of updating data across multiple collections in C#.
An example use case I have is that I have 2 collections:
- Collection 1 = Consoles
- Collection 2 = Games
The console collection looks like this: _id, Name, Year of Release, ThumbnailUrl, Enabled
The game collection looks something like this: _id, Name, Year Of Release, ThumbnailUrl, Console
Where the console sub-document looks like this: _id, Name, ThumbnailUrl
In SQL server world I would set this up a link and create an inner join to collect the data. However, in MongoDb I am taught to duplicate data.
How can I update the name of a console in the console collection and update all sub-documents to update the name of the console for the consoles with the identifier I've just modified in the console collection?
I am looking for an understanding of how I would go about this, and going forward I'm looking at adding more collections, all with similar sub-document references but need to be able to update everything as straightforward as possible.
CodePudding user response:
In mongodb we don't do that here,(embedded the whole document within another document). Reasons:
- It takes a lot space
- If the collection becomes too large it may exceed the doc size of mongodb which can cause problem
Instead we keep refrence of doc and not the whole or sub-document. for example in nodejs:
User
const userSchema = new Schema({
name: {
type: String,
default: null
},
phoneNumber: {
type: String,
default: null
},
email: {
type: String,
default: null
},
});
const user = mongoose.model("user", userSchema);
module.exports = user;
Family
const familySchema = new Schema({
familyName: {
type: String,
default: true
},
location:
{
type: String,
require: true
},
users: [
{
type: ObjectId,
ref: "user",
require: true
}
]
});
const family = mongoose.model("family", familySchema);
module.exports = family;
In this case we don't need to update the sub-document which is in your case you are maintaining instead we just update the original doc and the ref of that in the other document is serving the purpose of updating the doc for us.
Query
db.users.update(
{
_id: 1
},
{
$set: { name: "Ali" }
}
)