从文档中查找元素

时间:2019-01-14 12:19:42

标签: mongodb

我已将mysql数据库传递给mongoDB进行项目。我的数据库是关于药房的。我有一家工厂,那里有出售的药品清单。我试图找到销量最高的药物。

{
"_id" : ObjectId("5c3c71f2760c4f47c701fe13"),
"cliente" : {
    "tlmv" : "910987654",
    "nome" : "Josefina Vivida da Paz",
    "nif" : "122133144",
    "pontos" : NumberLong(0),
    "id" : NumberLong(2),
    "pass" : "1eab06cab995dfeb32b6b7c709b8a6c62cabacfe",
    "email" : "josefina@hotmail.pt"
},
"data_f" : ISODate("2018-06-03T00:00:01Z"),
"data_s" : ISODate("2018-06-02T23:55:59Z"),
"desconto" : 0,
"funcionario" : {
    "tlmv" : "934567123",
    "nome" : "Pedro Jorge Rito Lima",
    "ordenado" : 800.32,
    "iban" : "PT 50 2751 3262 76598707612",
    "pass" : "3cfa1c281281ffe4f5db2ccfbe7a17f8a9479808",
    "niss" : "14385639201",
    "id" : NumberLong(2),
    "cedula" : "54321"
},
"id" : NumberLong(15),
"id_c" : NumberLong(2),
"id_func" : NumberLong(2),
"medicamentos" : [
    {
        "categoria" : "Analg�sico",
        "receita" : "N",
        "des" : "Ben-U-Ron 500",
        "qt" : 20,
        "formato" : "granulado",
        "qt_v" : NumberLong(1),
        "pos" : "A12",
        "lab" : "Laborat�rio do Rio Ave",
        "preco_l" : 2.51,
        "un" : "un",
        "preco" : 2.51,
        "preco_v" : 2.51,
        "id" : NumberLong(1),
        "stock" : NumberLong(21)
    },
    {
        "categoria" : "Estatina",
        "receita" : "S",
        "des" : "Sinvastatina",
        "qt" : 30,
        "formato" : "comprimido",
        "qt_v" : NumberLong(1),
        "pos" : "K23",
        "lab" : "Mylan",
        "preco_l" : 16.45,
        "un" : "un",
        "preco" : 16.45,
        "preco_v" : 16.45,
        "id" : NumberLong(6),
        "stock" : NumberLong(25)
    }
],
"pontos_r" : NumberLong(10),
"pontos_u" : NumberLong(0),
"total" : 18.96

}

所以我的目标是计算每种药物-“ medicamento”-按不同的描述-“ des”排序。可以依靠mysql。有什么想法吗?上面的代码在1个工厂附近。

1 个答案:

答案 0 :(得分:1)

您需要$unwind才能获得每种药物的药品,然后$group$sum来获得每种药物的计数,请尝试:

db.collection.aggregate([
    {
        $unwind: "$medicamentos"
    },
    {
        $group: {
            _id: "$medicamentos.des",
            count: { $sum: 1 }
        }
    }
])