我有以下数据。我想使用 mongodb 聚合函数从下面显示的数据中提取 vendor 和客户。我想投影特定字段并从输出数据中删除其余字段。
{
"_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
}
我想提取所有同时也是 vendor 的业务合作伙伴的姓名。
在下面的表格中显示。
{
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
}
}
];
最佳答案
您可以$unwind
数组并使用$match
条件。
然后使用 $addToSet
将所有 vendor 添加到单个数组中。每个 _id
不会有重复的 vendor :
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'
}
}
}]);
这与 mongo 2.6 兼容(没有 $filter
)
它会给你这样的输出:
{
"_id": ObjectId("577f9a25bea25d480d8f1895"),
"supplier": [{
"name": "Ashish Kumar",
"dname": "jindal",
"email": "a@b.com",
"password": "12345",
"role": "supplier"
}]
}
关于javascript - mongodb 中带有投影字段的嵌套数组聚合查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510224/