用管道(聚合或更新)以特定索引将项目推入数组-MongoDB
受,我寻找了一种常见的做法,可以将项目插入管道内的特定索引中的数组,然后找不到一个。 假设我的文档看起来像:
[
{
_id: ObjectId("62c2e94e65f32725f8f62b79"),
updatedAt: ISODate("2022-06-29T13:10:36.659Z"),
createdAt: ISODate("2022-06-29T08:06:51.264Z"),
userID: 1,
myImage: "imageC",
images: [
"imageA",
"imageB",
"imageD",
"imageE",
"imageF"
]
}
]
我想将值插入字段 myimage
images array,specificaly in Index 2中,所以预期的结果是一个更新的文档:
[
{
_id: ObjectId("62c2e94e65f32725f8f62b79"),
updatedAt: ISODate("2022-06-29T13:10:36.659Z"),
createdAt: ISODate("2022-06-29T08:06:51.264Z"),
userID: 1,
myImage: "imageC",
images: [
"imageA",
"imageB",
"imageC",
"imageD",
"imageE",
"imageF"
]
}
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可以使用聚合管道或管道更新来完成。在这种情况下,简单的选项是更新管道。
这里的想法是在
$$ value
$ size 中使用$降低
步骤以找到正确的位置将项目插入到:查看其在
This can be done using an aggregation pipeline or an update with pipeline. In this case the simple option is an update pipeline.
The idea here is to use the
$size
of the$$value
in the$reduce
step to find the right place to insert the item into:See how it works on the playground example