如何在mongo中的所有嵌套文档中添加字段



我有一个具有树结构的文档:

{
"_id": "62e1f19f094a5696fd18f4e9",
"parent": null,
"children": [
{
"_id": "44e1f19f094a5696fd18f4o7",
"parent": "62e1f19f094a5696fd18f4e9",
"children": [
{
"_id": "62e1f19f094a5696fd18f4e9",
"parent": "44e1f19f094a5696fd18f4o7",
"children": []
}
] 
}
] 
}

我想为每个文档添加一个引用"_id"的新字段"id"(不带下划线(,即使它是子文档或父文档我试着做这样的事情:

$addFields: {id: $_id, children.id: $children._id}但in不起作用

所以,我想要得到的最终结果

{
"_id": "62e1f19f094a5696fd18f4e9",
"id": "62e1f19f094a5696fd18f4e9",
"parent": null,
"children": [
{
"_id": "44e1f19f094a5696fd18f4o7",
"id": "44e1f19f094a5696fd18f4o7",
"parent": "62e1f19f094a5696fd18f4e9",
"children": [
{
"_id": "62e1f19f094a5696fd18f4e9",
"id": "62e1f19f094a5696fd18f4e9",
"parent": "44e1f19f094a5696fd18f4o7",
"children": []
}
] 
}
] 
}

基于@rickhg12hs:的问题

这是可以做到的,但我同意@turivishal的观点,即如果你正在做这件事,那么将其存储一次是合理的(对查询的一个小更改(:

db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$function: {
body: "function drill(r) {r.id = r._id; if (r.children.length > 0) { for (let elem of r.children) { drill(elem)}} return r};",
args: [
"$$ROOT"
],
lang: "js"
}
}
}
}
])

看看它是如何在操场上工作的例子

对于数据库上的存储,使用带有管道的update而不是aggregate,如以下

最新更新