Last active
July 19, 2018 19:47
-
-
Save josemiguelq/be74f1d4f6a87acd92eb25d191685cdc to your computer and use it in GitHub Desktop.
Flat mongo query
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 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