2

Схема документа

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

На выходе хочется получить список документов:

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

Тестовый набор данных

Моя попытка сломалась на шаге "total count of ax": запрос, ответ

Пытался раскручивать, с помощью unwind, с флагом "preserveNullAndEmptyArrays", но на пустых массивах - ломается

1

1 ответ 1

1

Запрос

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"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

Ответ

/* 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
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.