【发布时间】:2017-06-23 19:44:58
【问题描述】:
我有以下数据。我想使用 mongodb 聚合函数从下面显示的数据中提取供应商和客户。我想投影特定字段并从输出数据中删除其余字段。
{
"_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
}
我想提取所有作为供应商的业务合作伙伴名称。
如下图所示。
{
suppliers:["Ashish Kumar"]
}
我想使用聚合查询来做到这一点。
我尝试的解决方案是。
[
{ $match: { "_id": ObjectId(req.headers["token"]) } },{
$project: {
suppliers: {
$filter: {
input: '$business_partner.role',
as: 'role',
cond: {"$eq":["$$bp.role","supplier"]}
}
},
_id: 0
}
}
];
【问题讨论】:
标签: javascript mongodb express mongoose aggregation-framework