我有一个打印机集合和printerInspection集合,其中包含打印机ID和检查日期。
我如何找到在08-23-2019未检查过的打印机(在此示例中,仅打印机2和1在08-23-2019进行了检查...
我目前使用的解决方案是在Java中同时提取集合和进行过滤,但是它非常缓慢,正在寻找mongo查询解决方案
db={
"printer": [
{
"printerId": 0
},
{
"printerId": 1
},
{
"printerId": 2
},
{
"printerId": 3
},
{
"printerId": 4
},
],
"printerInspection": [
{
"printerId": 2,
"date": "08-23-2019"
},
{
"printerId": 2,
"date": "08-22-2019"
},
{
"printerId": 2,
"date": "08-21-2019"
},
{
"printerId": 1,
"date": "08-23-2019"
},
{
"printerId": 3,
"date": "08-22-2019"
},
{
"printerId": 3,
"date": "08-21-2019"
}
]
}
答案 0 :(得分:3)
使用聚合管道如下 1.我们将所有可用的打印机和在指定日期检查的打印机合并在一起 2.打印机阵列与被检查打印机的区别
db.collection.aggregate([
{
$project: {
printers: {
$map: {
input: "$printer",
as: "item",
in: "$$item.printerId"
}
},
inspectedPrinters: {
$map: {
input: {
$filter: {
input: "$printerInspection",
as: "item",
cond: {
$eq: [
"$$item.date",
"08-23-2019"
]
}
}
},
as: "item2",
in: "$$item2.printerId"
},
}
}
},
{
$project: {
notInspected: {
$setDifference: [
"$printers",
"$inspectedPrinters"
]
}
}
}
])