I have a document with the following structure:
{
'_id': '',
'a': '',
'b': '',
'c': [
{
'_id': '',
'd': '',
'f': [
{
'orderDate': 12345,
'orderProfit': 12,
},
{
'orderDate': 67891,
'orderProfit': 12341,
},
{
'orderDate': 23456,
'orderProfit': 474,
},
],
},
{
'_id': '',
'd': '',
'f': [
{
'orderDate': 14232,
'orderProfit': 12222,
},
{
'orderDate': 643532,
'orderProfit': 4343,
},
{
'orderDate': 33423,
'orderProfit': 5555,
},
],
},
],
}
orderDate is an int64 that represents the date that an order was made
orderProfit is an int64 that represents the profit of an order
I needed to return the document that had the biggest "orderDate" and check if the "orderProfit" was the one i was looking for. For that matter I used a query like this (in an aggregate query):
[
{
'$addFields': {
'orders': {
'$map': {
'input': '$c',
'as': 'c',
'in': {
'profit': {
'$filter': {
'input': '$$c.f',
'cond': {
'$eq': [
{
'$max': '$$c.f.orderDate',
},
'$$this.orderDate',
],
},
},
},
},
},
},
},
},
{
'$match': {
'$or': [
{ 'orders.profit.orderProfit': 500 },
],
},
},
];
It is working properly.
The issue comes when trying to add this query to a countDocuments() query in order to fetch the total number of documents.
It is a requirement to use the countDocuments().
I just can't seem to make it work...
$addFields throws as an unknown top level operator. if I remove the $addFields then I can't add to the countDocuments() the query that finds the max date. If I totally remove it $match is an unknown operator.
db.getCollection('orders').countDocuments(
{
"orders.profit.orderProfit" : {"Query that was shown previously"}
})