How to return just the matched elements from a mongoDB array

半世苍凉 提交于 2019-12-05 14:50:18

This is possible through the aggregation framework. The pipeline passes all documents in the collection through the following operations:

$unwind operator - Outputs a document for each element in the produc array field by deconstructing it.

$match operator will filter only documents that match cod_zone criteria.

$group operator will group the input documents by a specified identifier expression and applies the accumulator expression $push to each group:

$project operator then reconstructs each document in the stream:

db.collection.aggregate([
    { 
        "$unwind": "$produc" 
    },
    {
        "$match": {
            "produc.cod_zone": "08850"
        }
    },
    {
       "$group":
         {
           "_id": null,
           "produc": { 
               "$push":  { 
                    "cod_prod": "$produc.cod_prod", 
                    "description": "$produc.description",
                    "price" : "$produc.price",
                    "current_stock" : "$produc.current_stock",
                    "min_stock" : "$produc.min_stock",
                    "cod_zone" : "$produc.cod_zone" 
               } 
            }
         }
     },
     {
         "$project": {
             "_id": 0,
             "produc": 1
         }
     }
])

will produce:

{
    "result" : [ 
        {
            "produc" : [ 
                {
                    "cod_prod" : "0001",
                    "description" : "Ordenador",
                    "price" : 400,
                    "current_stock" : 3,
                    "min_stock" : 1,
                    "cod_zone" : "08850"
                }, 
                {
                    "cod_prod" : "0004",
                    "description" : "Disco Duro",
                    "price" : 100,
                    "current_stock" : 20,
                    "min_stock" : 5,
                    "cod_zone" : "08850"
                }, 
                {
                    "cod_prod" : "0005",
                    "description" : "Monitor",
                    "price" : 150,
                    "current_stock" : 0,
                    "min_stock" : 2,
                    "cod_zone" : "08850"
                }
            ]
        }
    ],
    "ok" : 1
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!