I have the following data. I want to use mongodb aggregate function to extract suppliers and customers from the data shown below . I want to project specific fields and remove rest of the fields from 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 to extract all the business partners name who are suppliers also .
In the form show below .
{
suppliers:["Ashish Kumar"]
}
I want to do it using aggregation query .
The solution I tried is .
[
{ $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
your arrays and use $match
conditions. Then use $addToSet
to add all your supplier to a single array. There will be no supplier duplicate for 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 is compatible with mongo 2.6 (where there is no $filter
)
It will give you this kind of output :
{
"_id": ObjectId("577f9a25bea25d480d8f1895"),
"supplier": [{
"name": "Ashish Kumar",
"dname": "jindal",
"email": "a@b.com",
"password": "12345",
"role": "supplier"
}]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.