Document outline

doc_info: string wa:[ wa_flag: int ax:[ ax_info: string, de:[ type: int, value: int ] ] ] 

At the exit I want to get a list of documents:

 id doc_info count of wa where wa_flag in [1,2,3] total count of ax where wa_flag in [1,2,3] total count of de where wa_flag in [1,2,3] de.type == 10 and de.value > 2 de.type == 50 and de.value > 1 

Test data set

My attempt failed at the "total count of ax" step: request , response

Tried to unwind, using unwind, with the flag "preserveNullAndEmptyArrays", but on empty arrays - breaks

1 answer 1

Request

 db.getCollection('tost').aggregate([ { "$project":{ "_id": "$_id", "doc_info": 1, "wa_count": { "$sum":{ "$map":{ "input": "$wa", "as": "w", "in": { "$cond": [{ "$eq": ["$$w.wa_flag", 1]}, 1, 0] } } } }, "ax_count": { "$sum":{ "$map":{ "input": "$wa.ax", "as": "sub", "in": { "$size": "$$sub" } } } }, "de_count": { "$sum":{ "$map":{ "input": "$wa.ax", "as": "ax", "in": { "$sum":{ "$map":{ "input": "$$ax.de", "as": "de", "in": { "$size": "$$de" } } } } } } } } } ]) 

Answer

 /* 1 */ { "_id" : ObjectId("57a48c571b252bcce6cab8aa"), "doc_info" : "info_1", "wa_count" : 0, "ax_count" : 0, "de_count" : 0 } /* 2 */ { "_id" : ObjectId("57a48c611b252bcce6cab8ab"), "doc_info" : "info_2", "wa_count" : 1.0, "ax_count" : 0, "de_count" : 0 } /* 3 */ { "_id" : ObjectId("57a48c691b252bcce6cab8ac"), "doc_info" : "info3", "wa_count" : 2.0, "ax_count" : 6, "de_count" : 0 } /* 4 */ { "_id" : ObjectId("57a48c731b252bcce6cab8ad"), "doc_info" : "info4", "wa_count" : 1.0, "ax_count" : 2, "de_count" : 4 }