您好,我是mongoDB的新手,我希望将一些数据汇总到一个将使用 $ out 创建的数据中。基本上,我有一个数据集合,其中的信息存储在数组中,如果相同的数据至少已插入到数组中一次,我想将数据放入新的集合中。最好的功能是执行此操作。我正在查看 $ filter 和 $ elemMatch 。
基本上,如果卡车的注册号中的任何一个至少出现在任何用户类型的机械师 maintenances 数组中,那么我想将该信息保存到新集合中类似于{“ registration”:“ truck-registration”},没有重复项。
什么是最好的方法?
这些只是许多数据库插入中的一部分(用户很多,卡车也很多)。
卡车
db.transport.insert ( {"_id":"GFT008", "TRUCK": { "registration":"GFT008", "capacity":40000, "weight":15000, "status":"AVAILABLE"} });
db.transport.insert ( {"_id":"PKR008", "TRUCK": { "registration":"PKR008", "capacity":22000, "weight":8800, "status":"AVAILABLE"} });
db.transport.insert ( {"_id":"QRT834", "TRUCK": { "registration":"QRT834", "capacity":5550, "weight":400, "status":"USED"} } );
员工
db.transport.insert ( {"_id":"6", "EMPLOYEE": { "e#":"6", "name":"Michael Jones", "dob":"05-OCT-65", "address":"23 Waterloo Ave. Surry Hills, NSW 2502", "hiredate":"12-JAN-93","position":"mechanic","licence":"7773","status":"ON_LEAVE","experience":"STANDARD","maintenances":[{"registration":"QRT834","time":"40","maintenance date":"12-JUN-99"},{"registration":"QRT834","time":"40","maintenance date":"15-JUN-98"},{"registration":"SYF777","time":"30","maintenance date":"01-AUG-98"},{"registration":"SYF777","time":"30","maintenance date":"05-AUG-95"},{"registration":"SYF777","time":"30","maintenance date":"06-AUG-00"},{"registration":"LUCY01","time":"200","maintenance date":"12-MAR-97"},{"registration":"SYF777","time":"30","maintenance date":"02-AUG-00"},{"registration":"PKR768","time":"200","maintenance date":"12-AUG-00"},{"registration":"QRT834","time":"200","maintenance date":"30-JUN-00"},{"registration":"SYF777","time":"300","maintenance date":"02-AUG-02"},{"registration":"PKR768","time":"460","maintenance date":"12-AUG-02"},{"registration":"LUCY01","time":"40","maintenance date":"29-JUL-02"},{"registration":"QRT834","time":"40","maintenance date":"30-JUN-02"}]} } );
答案 0 :(得分:1)
看看:
MongoPlayground上的实时演示
db.employee.aggregate([
{
$unwind: "$EMPLOYEE.maintenances"
},
{
$lookup: {
from: "transport",
localField: "EMPLOYEE.maintenances.registration",
foreignField: "TRUCK.registration",
as: "matches"
}
},
{
$match: {
"matches": {
$size: 1
}
}
},
{
$group: {
_id: "$EMPLOYEE.maintenances.registration",
}
}
])
这是一个多阶段聚合: -展开数组 -加入运输记录的放松阶段 -筛选完全匹配(?)的记录 -最后-通过分组删除重复项
结果:
[{"_id": "QRT834"}]