i have following data. want use mongodb aggregate function extract suppliers , customers data shown below . want project specific fields , remove rest of fields output data.
{ "_id" : objectid("577f9a25bea25d480d8f1895"), "password" : "12345", "mobile" : "9582223889", "email" : "a@b.com", "name" : "ashiush jindal", "invoice" : [{ "name" : "ashish jindal", "dname" : "jindalbe", "email" : "a@b.com", "password" : "12345", "role" : ["customer"] }], "inventory" : [{ }, { "item" : "levis jeans", "sku" : "12345", "buy" : [{ "bp" : "jindalbe", "qty" : 50, "created" : "9/7/2016" }] }, { "item" : "levis trouser", "sku" : "123", "selling_price" : 2000, "buy" : [{ "bp" : "jindalbe", "qty" : 90, "created" : "9/7/2016", "price_per_qty" : 1000 }, { "bp" : "jindalbe", "qty" : 60, "created" : "9/7/2016", "price_per_qty" : 1000 }, { "bp" : "jindalbe", "qty" : 60, "created" : "9/7/2016", "price_per_qty" : 1000 }, { "bp" : "jindalbe", "qty" : 60, "created" : "9/7/2016", "price_per_qty" : 1000 }, { "bp" : "jindalbe", "qty" : 60, "created" : "9/7/2016", "price_per_qty" : 5000 }, null] }], "business_partner" : [{ "name" : "ashish jindal", "dname" : "jindalbe", "email" : "a@b.com", "password" : "12345", "role" : ["customer"] }, { "name" : "ashish jindal", "dname" : "jindalbe", "email" : "a@b.com", "password" : "12345", "role" : ["customer"] }, { "name" : "ashish kumar", "dname" : "jindal", "email" : "a@b.com", "password" : "12345", "role" : ["supplier"] }], "__v" : 0 }
i want extract business partners name suppliers .
in form show below .
{ suppliers:["ashish kumar"] }
i want using aggregation query .
the solution tried .
[ { $match: { "_id": objectid(req.headers["token"]) } },{ $project: { suppliers: { $filter: { input: '$business_partner.role', as: 'role', cond: {"$eq":["$$bp.role","supplier"]} } }, _id: 0 } } ];
you can $unwind
arrays , use $match
conditions. use $addtoset
add supplier single array. there no supplier duplicate each _id
:
db.device.aggregate([{ "$unwind": "$business_partner" }, { "$unwind": "$business_partner.role" }, { "$match": { "_id": objectid("577f9a25bea25d480d8f1895"), "business_partner.role": "supplier" } }, { "$project": { "_id": 1, "business_partner": 1 } },{ "$group": { _id:"$_id", supplier: { $addtoset: '$business_partner' } } }]);
this compatible mongo 2.6 (where there no $filter
)
it give kind of output :
{ "_id": objectid("577f9a25bea25d480d8f1895"), "supplier": [{ "name": "ashish kumar", "dname": "jindal", "email": "a@b.com", "password": "12345", "role": "supplier" }] }
Comments
Post a Comment