我正在嘗試在 MongoDB 嵌套陣列中進行查找。我的資料看起來像。
[
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636b9fcbda6d2b17f5cae0",
"month": "2022-05",
"shift": [
{
"date": "2022-05-01",
"shiftId": "622bb0f4b88dc92e3c2cac56"
},
{
"date": "2022-05-02",
"shiftId": "622b55f8f59dcdd1ab9b36b1"
},
]
}
},
{
"_id": "62626a7446ba9a911a623b37",
"name": "Pinki Das",
"shifts": {
"_id": "62636ba4cbda6d2b17f5cae1",
"month": "2022-05",
"shift": [
{
"date": "2022-05-01",
"shiftId": "622bb0f4b88dc92e3c2cac56"
}
]
}
}
]
我正在嘗試查找。
{
"$lookup": {
"from": "shifts",
"localField": "shifts.shift.shiftId",
"foreignField": "_id",
"as": "shifts.shift.shiftId"
}
}
并得到結果。
[
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636b9fcbda6d2b17f5cae0",
"month": "2022-05",
"shift": {
"date": "2022-05-01",
"shiftId": [
{
"_id": "622bb0f4b88dc92e3c2cac56",
"date": "2022-05-01",
"name": "Day"
}
]
}
}
},
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636b9fcbda6d2b17f5cae0",
"month": "2022-05",
"shift": {
"date": "2022-05-02",
"shiftId": [
{
"_id": "622b55f8f59dcdd1ab9b36b1",
"date": "2022-05-02",
"name": "Morning"
}
]
}
}
},
{
"_id": "62626a7446ba9a911a623b37",
"name": "Pinki Das",
"shifts": {
"_id": "62636ba4cbda6d2b17f5cae1",
"month": "2022-05",
"shift": {
"date": "2022-05-01",
"shiftId": [
{
"_id": "622bb0f4b88dc92e3c2cac56",
"date": "2022-05-01",
"name": "Day"
}
]
}
}
}
]
但我需要的資料應該如下所示。shiftId應該與班次資料一起嵌套在班次陣列下。
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636b9fcbda6d2b17f5cae0",
"month": "2022-05",
"shift": [
{
"date": "2022-05-01",
"shiftId": [
{
"_id": "622bb0f4b88dc92e3c2cac56",
"date": "2022-05-01",
"name": "Day"
}
]
},
{
"date": "2022-05-02",
"shiftId": [
{
"_id": "622b55f8f59dcdd1ab9b36b1",
"date": "2022-05-02",
"name": "Morning"
}
]
}
]
}
},
{
"_id": "62626a7446ba9a911a623b37",
"name": "Pinki Das",
"shifts": {
"_id": "62636ba4cbda6d2b17f5cae1",
"month": "2022-05",
"shift": {
"date": "2022-05-01",
"shiftId": [
{
"_id": "622bb0f4b88dc92e3c2cac56",
"date": "2022-05-01",
"name": "Day"
}
]
}
}
}
]
這是缺少班次下的日期欄位。并且還需要對移位陣列進行分組。請幫幫我。操場
uj5u.com熱心網友回復:
$set之后使用$lookup
db.employees.aggregate([
{
$lookup: {
from: "shifts",
localField: "shifts.shift.shiftId",
foreignField: "_id",
as: "shifts.shift2"
}
},
{
$set: {
"shifts.shift": {
$map: {
input: "$shifts.shift",
as: "s",
in: {
$mergeObjects: [
"$$s",
{
shiftId: {
$filter: {
input: "$shifts.shift2",
as: "s2",
cond: { $eq: [ "$$s2._id", "$$s.shiftId" ] }
}
}
}
]
}
}
}
}
},
{
$unset: [ "shifts.shift2" ]
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/465231.html
