gpt4 book ai didi

mongodb - 克隆并重命名 Mongodb 中子文档数组的字段

转载 作者:行者123 更新时间:2023-12-04 07:51:11 25 4
gpt4 key购买 nike

我有一个这样的集合:

{
name: "A Name",
answers: [
{order: 1},
{order: 2},
{order: 3}
]
}
我想要做的是添加一个新的文件 idanswers 的每个元素基于 order 的值的数组属性 - 我只想克隆它,所以输出是
{
name: "A Name",
answers: [
{order: 1, id: 1},
{order: 2, id: 2},
{order: 3, id: 3}
]
}
我看了 this postthis one也是,但我不知道如何将它们组合起来才能正常用于子文档。
aggregate 的 MongoDB 文档中方法,我找到了一个如何更新嵌入文档的简单示例 here ,但我不知道如何使用 order属性(property)而不是固定期限。以下尝试似乎无法按我的需要工作:
db.collection.aggregate([
{
$addFields: {
"answers.id": "answers.$.order"
}
}
])

db.collection.aggregate([
{
$addFields: {
"answers.id": "$answers.order"
}
}
])
使用`aggregate 方法是否可以达到预期的结果?

最佳答案

演示 - https://mongoplayground.net/p/M79MV6-Zp4C

db.collection.aggregate([
{
$set: {
answers: {
$map: {
input: "$answers",
as: "answer",
in: { $mergeObjects: [ "$$answer", { id: "$$answer.order" } ]
}
}
}
}
}
])

更新演示 - https://mongoplayground.net/p/iyqIPGQ5-ld
db.collection.aggregate([
{ $unwind: "$answers" },
{
$group: {
_id: "$_id",
answers: { $push: { order: "$answers.order", id: "$answers.order" } },
name: { $first: "$name" } // preserve properties add them to the group pick 1st value
}
}
])

演示 - https://mongoplayground.net/p/Ln5CcmT-Kkm
db.collection.aggregate([
{ $unwind: "$answers" }, // break into individuals documents
{ $addFields: { "answers.id": "$answers.order" } }, // copy order value to id
{ $group: { _id: "$_id", answers: { $push: "$answers" } } } // join and group it back
])

如果你想排序 n 从索引中获取 id
演示 - https://mongoplayground.net/p/6U_sRYWHtDR
db.collection.aggregate([
{ $sort: { "answers.order": 1 } },
{ $unwind: { path: "$answers", includeArrayIndex: "index" } },
{ $group: { _id: "$_id", answers: { "$push": { order: "$answers.order", id: { $add: [ "$index", 1 ] } } } } }
])

关于mongodb - 克隆并重命名 Mongodb 中子文档数组的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66970322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com