Created
July 20, 2018 16:49
-
-
Save josemiguelq/f665504ee4fe7a7c67cb3a4e08b1d3c8 to your computer and use it in GitHub Desktop.
mongo flat and insert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var file = cat('path/to/yourFile.txt'); | |
var lastQuery = new Date(); | |
var docs = db.getCollection("sales").aggregate([ | |
{$match : {createdAt : {$gte : lastQuery}} } | |
{$unwind : '$createdAt'}, | |
{$unwind : '$updatedAt'}, | |
{$unwind : '$services'}, | |
{$group : { | |
_id : {'service' : '$services', 'user' : '$user', 'pointOfSale' : '$pointOfSale', 'createdAt' : '$createdAt', 'updatedAt' : '$updatedAt'}} | |
}, | |
{$project : { | |
service : "$_id.service", | |
user : "$_id.user", | |
pointOfSale:"$_id.pointOfSale", | |
createdAt:"$_id.createdAt", | |
updatedAt:"$_id.updatedAt", | |
"_id":0 | |
} | |
} , | |
{$project : { | |
'service.log' : 0, | |
'user.integrationCredentials' : 0, | |
'service.customer.email' : 0, | |
'service.customer.birthday' : 0, | |
'pointOfSale.network.availableServices' : 0, | |
'pointOfSale.integrationIdentifiers' : 0, | |
'pointOfSale.operatorIdentifiers' : 0, | |
}} | |
]).map( function (record) { | |
var newObj = {}; | |
var currentKey = ""; | |
dive(currentKey,record,newObj); | |
function dive (currentKey,record,newObj){ | |
for (var i in record) { | |
if (record.hasOwnProperty(i)) { | |
var newKey = i; | |
var newVal = record[i]; | |
if (currentKey.length > 0) { | |
newKey = currentKey + '_' + i; | |
} | |
if (newKey === 'createdAt' || newKey === 'updatedAt') { | |
newObj[newKey] = newVal; | |
} | |
if (typeof newVal === "object") { | |
dive(newKey, newVal, newObj); | |
} else { | |
newObj[newKey] = newVal; | |
} | |
} | |
} | |
} | |
return newObj; | |
}) | |
db.sales_reports.drop(); | |
db.sales_reports.insertMany(docs) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment