Hi @Jose_Olaizola,
Based off your sample documents you’ve provided, it appears Cost and Revenue are within another field named "fields".
Let’s say I have the following documents (copied from what you provided):
db.collection.find({},{_id:0})
[
{
fields: {
'Entry Date': '2023-12-14T01:48:22.000Z',
Cost: 30,
Revenue: 1225
}
},
{
fields: { 'Entry Date': '2023-11-06T22:40:02.000Z', Revenue: 1125 }
},
{ fields: { 'Entry Date': '2023-11-21T22:24:31.000Z', Cost: 0.75 } }
]
If I try perform the $match with for a field named "$Revenue" (based off the above documents):
db.collection.aggregate({$match:{'$Revenue':{'$ne':null}}})
Uncaught:
MongoServerError: unknown top level operator: $Revenue. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.
I assume you’re wanting the resulting document to be something like the below (correct me if I am wrong in my assumption here):
{
"_id" : null,
"Profittest": 2319.25
}
Calculated that as just using the "fields.Revenue" values summed minus the "fields.Cost" values summed.
If the above is correct, you should be able to achieve it with something like:
db.collection.aggregate([
{
'$match': {
'$or': [
{ 'fields.Revenue': { '$ne': null } },
{ 'fields.Cost': { '$ne': null } }
]
}
},
{
'$group': {
_id: null,
TotalRevenue: { '$sum': '$fields.Revenue' },
TotalCost: { '$sum': '$fields.Cost' }
}
},
{
'$project': { Profittest: { '$subtract': [ '$TotalRevenue', '$TotalCost' ] } }
}
])
Which results in (for the provided sample documents):
[ { _id: null, Profittest: 2319.25 } ]
I’ve only tested the above based off the sample documents so you may wish to try this out on a test system with more data to verify theres no odd behaviour. Additionally, it may be easier to add the corresponding fields.Revenue and fields.Cost fields to documents that do not have them (and set the value to 0 as you had mentioned). This will simplify the query although you’d need to change it from the above one if you plan to do so.
I’ve not yet tried this on charts itself as the above tests were done via mongosh but if you still need further help let me know and I will attempt to do this via Charts – If further assistance is required, let me know your expected output on Charts based off the sample documents mentioned here.
Regards,
Jason