【发布时间】:2021-09-10 17:48:10
【问题描述】:
我的聚合查询中有这个简单的$project 用于返回每个 产品项的第一个图像(字符串)元素并将其存储在first 字段中。
{
$project: {
'products._id': 1,
'products.images': 1,
'products.first': { $arrayElemAt: ['$products.images', 0] },
},
}
但是,当我执行查询时,它会将 first 字段设置为第一个产品的整个图像数组的值。
期望的结果:
{
"_id": "60d9adda7f017440403d57fb",
"products": [
{
"_id": "5e48a95545f3350017aecce0",
"images": ["image1","image2"],
"first": "image1"
},
{
"_id": "5e4c0b0986c1d0001757ae06",
"images": ["image3"],
"first": "image3"
},
{
"_id": "5e4c0e1c86c1d0001757ae07",
"images": ["image4"],
"first": "image4"
}
]
}
实际结果:
{
"_id": "60d9adda7f017440403d57fb",
"products": [
{
"_id": "5e48a95545f3350017aecce0",
"images": ["image1","image2"],
"first": ["image1", "image2"]
},
{
"_id": "5e4c0b0986c1d0001757ae06",
"images": ["image3"],
"first": ["image1", "image2"]
},
{
"_id": "5e4c0e1c86c1d0001757ae07",
"images": ["image4"],
"first": ["image1", "image2"]
}
]
}
请问,我该如何解决?
谢谢。
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query