条件聚合阶段
Conditional aggregation stage
我们有 3 个集合来跟踪一个机械车间。
PARTS
根据 shopID
给出商品总数
我们需要确认 INPROCESS
和 REJECT
中的商品总和是否等于 PARTS
中商店的数量。
但是,我们会去研究 REJECT
- 仅当 INPROCESS
不等于计数时,从而节省查找。
如何实现。
PARTS
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"count": 200,
}
INPROCESS
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "5647",
},
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "2314",
},
REJECTED
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "xxxx",
},
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "yyyy",
},
试试这个:
db.PARTS.aggregate([
{
$lookup: {
from: "INPROCESS",
localField: "shop",
foreignField: "shop",
as: "inprocess"
}
},
{
$match: {
$expr: {
$ne: [
"$count",
{
$size: "$inprocess"
}
]
}
}
},
{
$lookup: {
from: "REJECTED",
localField: "shop",
foreignField: "shop",
as: "rejected"
}
},
{
$match: {
$expr: {
$ne: [
"$count",
{
$add: [
{
$size: "$inprocess"
},
{
$size: "$rejected"
}
]
}
]
}
}
}
])
我们有 3 个集合来跟踪一个机械车间。
PARTS
根据 shopID
给出商品总数
我们需要确认 INPROCESS
和 REJECT
中的商品总和是否等于 PARTS
中商店的数量。
但是,我们会去研究 REJECT
- 仅当 INPROCESS
不等于计数时,从而节省查找。
如何实现。
PARTS
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"count": 200,
}
INPROCESS
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "5647",
},
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "2314",
},
REJECTED
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "xxxx",
},
{
"_id": ObjectId("xxxxxx"),
"shop": "Q4",
"itemID": "yyyy",
},
试试这个:
db.PARTS.aggregate([
{
$lookup: {
from: "INPROCESS",
localField: "shop",
foreignField: "shop",
as: "inprocess"
}
},
{
$match: {
$expr: {
$ne: [
"$count",
{
$size: "$inprocess"
}
]
}
}
},
{
$lookup: {
from: "REJECTED",
localField: "shop",
foreignField: "shop",
as: "rejected"
}
},
{
$match: {
$expr: {
$ne: [
"$count",
{
$add: [
{
$size: "$inprocess"
},
{
$size: "$rejected"
}
]
}
]
}
}
}
])