Тип преобразования документа - PullRequest
2 голосов
/ 03 октября 2019

Допустим, у меня есть документ mongodb

{
  "id" : 1,
  "types" : ["online" ,"offline"],
  "applications" : [ ["online", "online"], ["offline"] ]
}

Я хотел бы преобразовать в

{
"id" : 1,
"types" : [
        {
          "type" : "online",
          "count" : 2,
          "applications" : [ "online", "online"]
        },
        {
          "type" : "offline",
          "count" : 1,
          "applications" : [ "offline" ]
        }
    ]
}

, здесь типы и типы массивов приложений могут быть любого размера.

1 Ответ

1 голос
/ 04 октября 2019

Вы можете сделать это в два шага, использовать $ map с $ filter , чтобы сопоставить type с applications, а затем запустить $ уменьшить доget count:

db.collection.aggregate([
    {
        $project: {
            id: 1,
            types: {
                $map: {
                    input: "$types",
                    as: "type",
                    in: {
                        type: "$$type",
                        applications: {
                            $filter: {
                                input: "$applications",
                                as: "application",
                                cond: { 
                                    $allElementsTrue: {
                                        $map: { input: "$$application", in: { $eq: [ "$$this", "$$type" ] } }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    {
        $addFields: {
            types: {
                $map: {
                    input: "$types",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { 
                                count: { 
                                    $reduce: { 
                                        input: "$$this.applications", 
                                        initialValue: 0, 
                                        in: { $add: [ "$$value", { $size: "$$this" }  ] } 
                                    }
                                } 
                            }
                        ]
                    }
                }
            }
        }
    }
])

Вы можете решить, лучше ли использовать $ allElementsTrue или $ anyElementTrue при построении критериев фильтрации.

Детская площадка Монго

...