[英]Mongo DB - map relational data to document structure
我有一個在mongo集合中包含3000萬行的數據集。 一組記錄示例為:
{"_id" : ObjectId("568bc0f2f7cd2653e163a9e4"),
"EmailAddress" : "1234@ab.com",
"FlightNumber" : 1043,
"FlightTime" : "10:00"},
{"_id" : ObjectId("568bc0f2f7cd2653e163a9e5"),
"EmailAddress" : "1234@ab.com",
"FlightNumber" : 1045,
"FlightTime" : "12:00"},
{"_id" : ObjectId("568bc0f2f7cd2653e163a9e6"),
"EmailAddress" : "5678@ab.com",
"FlightNumber" : 1045,
"FlightTime" : "12:00"},
它是直接從SQL Server導入的,因此具有數據關系的特性。
如何最好地將此數據映射到另一個集合,以便所有數據然后通過嵌套了FlightNumbers的EmailAddress分組? 輸出示例如下:
{"_id" : ObjectId("can be new id"),
"EmailAddress" : "1234@ab.com",
"Flights" : [{"Number":1043, "Time":"10:00"},{"Number":1045, "Time":"12:00"}]},
{"_id" : ObjectId("can be new id"),
"EmailAddress" : "5678@ab.com",
"Flights" : [{"Number":1045, "Time":"12:00"}]},
我一直在研究一個導入路由,該路由會遍歷源集合中的每個記錄,然后批量插入第二個集合中。 這樣做工作正常,但是除非我對記錄進行后退處理,否則不允許我對數據進行分組,這會增加導入例程的大量時間開銷。
此代碼為:
var sourceDb = db.getSiblingDB("collectionSource");
var destinationDb = db.getSiblingDB("collectionDestination");
var externalUsers=sourceDb.CRM.find();
var index = 0;
var contactArray = new Array();
var identifierArray = new Array();
externalUsers.forEach(function(doc) {
//library code for NewGuid omitted
var guid = NewGuid();
//buildContact and buildIdentifier simply create 2 js objects based on the parameters
contactArray.push(buildContact(guid, doc.EmailAddress, doc.FlightNumber));
identifierArray.push(buildIdentifier(guid, doc.EmailAddress));
index++;
if (index % 1000 == 0) {
var now = new Date();
var dif = now.getTime() - startDate.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
print("Written " + index + " items (" + Seconds_Between_Dates + "s from start)");
}
//bulk insert in batches
if (index % 5000 == 0) {
destinationDb.Contacts.insert(contactArray);
destinationDb.Identifiers.insert(identifierArray);
contactArray = new Array();
identifierArray = new Array();
}
});
提前謝謝了
嘿,歡迎來到MongoDB。 在這種情況下,您可能要考慮使用兩個不同的集合-一個用於用戶,一個用於航班。
用戶:
{
_id:
email:
}
飛行:
{
_id:
userId:
number: // if number is unique, you can actually specify _id as number
time:
}
在forEach循環中,您首先要檢查是否存在具有該特定電子郵件地址的用戶文檔。 如果沒有,請創建它。 然后,使用用戶文檔的唯一標識符將新文檔插入Flights集合中,並將該標識符存儲在字段userId
(或者也許passengerId
?)下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.