我是MongoDB的新手。我试图在多标签嵌套数组查找。我的数据如下所示。
[
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636b9fcbda6d2b17f5cae0",
"month": "2022-05",
"shift": [
{
"date": "2022-05-01",
"shiftId": "622bb0f4b88dc92e3c2cac56"
}
]
}
},
{
"_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": {
"shiftId": [
{
"_id": "622bb0f4b88dc92e3c2cac56",
"name": "Day"
}
]
}
}
},
{
"_id": "62626a7446ba9a911a623b37",
"name": "Pinki Das",
"shifts": {
"_id": "62636ba4cbda6d2b17f5cae1",
"month": "2022-05",
"shift": {
"shiftId": [
{
"_id": "622bb0f4b88dc92e3c2cac56",
"name": "Day"
}
]
}
}
}
]
但是我的期望数据应该看起来像下面。
[
{
"_id": "621eedae92979fd8f0e9451d",
"name": "Pallab Koley",
"shifts": {
"_id": "62636b9fcbda6d2b17f5cae0",
"month": "2022-05",
"shift": [
{
"date": "2022-05-01",
"shiftId": {
"_id": "622bb0f4b88dc92e3c2cac56",
"name": "Day"
}
}
]
}
},
{
"_id": "62626a7446ba9a911a623b37",
"name": "Pinki Das",
"shifts": {
"_id": "62636ba4cbda6d2b17f5cae1",
"month": "2022-05",
"shift": [
{
"date": "2022-05-01",
"shiftId": {
"_id": "622bb0f4b88dc92e3c2cac56",
"name": "Day"
}
}
]
}
}
]
为shifts.shift
下缺失的date
域。shiftId
正在替换移位阵列下的所有场。请帮帮我。mongoplayground
用查找结果重写数组的原始内容。考虑使用子管道将日期存储为变量,并将其赋值给查找结果。
db.employees.aggregate([
{
"$unwind": "$shifts.shift"
},
{
"$lookup": {
"from": "shifts",
"let": {
shiftDate: "$shifts.shift.date",
sid: "$shifts.shift.shiftId"
},
"pipeline": [
{
"$match": {
$expr: {
"$eq": [
"$_id",
"$$sid"
]
}
}
},
{
"$addFields": {
"date": "$$shiftDate"
}
}
],
"as": "shifts.shift.shiftId"
}
}
])
这是Mongo游乐场供您参考。
对不起,我把我的要求写错了。我把操场改成了多班制。改造后的操场。结果应该如下图所示。
{
"_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"
}
]
}
}
}
]