我做了以下查詢:
db.employees.aggregate([
{
$match: {
isActive: true,
}
},
{
$lookup: {
from: 'shifts',
localField: '_id',
foreignField: 'employee',
as: 'shifts'
}
},
{
$unwind: {
path: '$shifts',
preserveNullAndEmptyArrays: true,
}
}
])
現在得到以下結果:
[
{
"_id": "621eedae92979fd8f0e9451d",
“名稱”:“帕拉布·科利”,
“轉移”: {
"_id": "62636b9fcbda6d2b17f5cae0",
"月": "2022-05",
“轉移”: [
{
“日期”:“2022-05-01”,
“shiftId”:“622bb0f4b88dc92e3c2cac56”
}
]
}
},
{
"_id": "621eedae92979fd8f0e9451d",
“名稱”:“帕拉布·科利”,
“轉移”: {
"_id": "62636bb3cbda6d2b17f5cae2",
"月": "2022-04",
“轉移”: [
{
“日期”:“2022-04-01”,
“shiftId”:“622bb0f4b88dc92e3c2cac56”
}
]
}
},
{
"_id": "62626a7446ba9a911a623b37",
"name": "Pinki Das",
“轉移”: {
"_id": "62636ba4cbda6d2b17f5cae1",
"月": "2022-05",
“轉移”: [
{
“日期”:“2022-05-01”,
“shiftId”:“622bb0f4b88dc92e3c2cac56”
}
]
}
}
]
我需要過濾我要添加的特定月份的資料
{
$unwind: {
path: '$shifts',
preserveNullAndEmptyArrays: true,
}
},
{
$match: {
"shifts.month": “2022-04”
}
},
我得到了結果
[
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636bb3cbda6d2b17f5cae2",
"month": "2022-04",
"shift": [
{
"date": "2022-04-01",
"shiftId": "622bb0f4b88dc92e3c2cac56"
}
]
}
}
]
但我的要求是,我需要員工集合中的所有其他現有員工,即使輪班集合中也沒有記錄。請幫助得到那個。?
uj5u.com熱心網友回復:
可能這就是你需要的。
$match階段$lookup階段- 移除
$unwind舞臺。 $projectstage - 使用$filter運算子過濾shifts陣列中的檔案,month即2022-04.
db.collection.aggregate([
// $match ,
// $lookup,
// Remove $unwind
{
$project: {
id: 1,
name: 1,
shifts: {
"$filter": {
"input": "$shifts",
"cond": {
$eq: [
"$$this.month",
"2022-04"
]
}
}
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462440.html
上一篇:Mongoose-只計算某些檔案
下一篇:串列不會按日期排序
