I have 3 table in SQL that have many-to-many relation.The first table “account” have 3 field (AccountId,UserName,Email).The second table “device” have 2 field (DeviceId and DeviceCode) and table “Association” have 4 field (AccountId,DeviceId,LastActivityDate,HasException)
How to convert them to mongoDB.
From suggestion of mongodb.org I embed collection “Associaton” into device collection and account collection but the field “LastAccessDate” always was updated every time when my system have new transaction.
-Account collection:
{
“UserName” : “xxx”,
“Email” : 1,
“Association” : [{
“DeviceId” : “4f45c4b73174ec818148d5c5”,
“LastActivityDate” : “Thu, 23 Feb 2012 11:44:19 GMT +07:00”,
“HasException” : false
}, {
“DeviceId” : ObjectId(“4f45c5e93174ec818148d5c7”),
“LastActivityDate” : “Thu, 23 Feb 2012 11:52:05 GMT +07:00”,
“Exception” : null
}]
}
Device collection:
{
“DeviceCode” : “abcjxhcbxkjcnxkcjhdiofjdojdlkdknd”,
“Associations” : [{
“AccountId” : “34fdgfdy5676”,
“LastActivityDate” : “02/03/2012”,
“HasException” : false
}, {
“AccountId” : “34fdgfdy5dd676”,
“LastActivityDate” : “02/03/2012”,
“HasException” : true
}],
}
I see multiple solutions for your problem:
Seldom updates
To avoid joins, that have to be done client-side in NoSQL databases, put everything into one collection. If you do not update very often, you could do
This results in duplicate data, but if performance (no joins) comes before memory efficiency, it’s probably a suitable solution for you. Since the data is stored multiple times, updates are more demanding for the server. I.e. updating the Email address would look like
As you don’t need the AccountID and DeviceID to join anymore, you can also drop these two fields.
Frequent updates
When you have frequent updates, instead of embedding, you could use References. I think you have to resolve them client-side. You then have three collections:
Account:
Device:
Association:
You don’t have any duplication this way, but you have to deal with references.