mongodb aggregate聚合管道指定关联查询筛选字段
mongodb aggregate聚合管道指定关联查询筛选字段
db.order.aggregate([
{
$lookup:
{
from: "order_item",
localField: "order_id",
foreignField: "order_id",
as: "items"
}
},
{
$match:{"all_price":{$gte:90}}
},{
$project:{order_id:1,uid:1,trade_no:1,all_price:1,all_num:1,cate:{ items:1,price:1}}
}
])
返回结果:
{
"_id": ObjectId("5b743d8c2c327f8d1b360540"),
"order_id": "1",
"uid": 10,
"trade_no": "111",
"all_price": 100,
"all_num": 2,
"items": [{
"_id": ObjectId("5b743d9c2c327f8d1b360543"),
"title": "商品鼠标1",
"price": 50,
}, {
"_id": ObjectId("5b743da12c327f8d1b360544"),
"title": "商品键盘2",
"price": 50,
}, {
"_id": ObjectId("5b74f457089f78dc8f0a4f3b"),
"title": "商品键盘3",
"price": 0,
}]
} {
"_id": ObjectId("5b743d902c327f8d1b360541"),
"order_id": "2",
"uid": 7,
"trade_no": "222",
"all_price": 90,
"all_num": 2,
"items": [{
"_id": ObjectId("5b743da52c327f8d1b360545"),
"title": "牛奶",
"price": 50,
}, {
"_id": ObjectId("5b743da92c327f8d1b360546"),
"title": "酸奶",
"price": 40,
}]
} {
"_id": ObjectId("5b743d962c327f8d1b360542"),
"order_id": "3",
"uid": 9,
"trade_no": "333",
"all_price": 20,
"all_num": 6,
"items": [{
"_id": ObjectId("5b743dad2c327f8d1b360547"),
"title": "矿泉水",
"price": 2
}, {
"_id": ObjectId("5b743dff2c327f8d1b360548"),
"title": "毛巾",
"price": 10,
}]
}```
3 回复
https://docs.mongodb.com/v3.2/reference/operator/aggregation/lookup/index.html
db.orders.aggregate([
{
$unwind: "$specs"
},
{
$lookup:
{
from: "inventory",
localField: "specs",
foreignField: "size",
as: "inventory_docs"
}
},
{
$match: { "inventory_docs": { $ne: [] } }
}
])
{ $project: {
module_name: 1,
adoc: {
$filter:{
input:'$adoc',
as:'item',
cond:{$eq:['$$item.status',1]}
},
}
}
},