【发布时间】:2023-03-05 20:37:01
【问题描述】:
说明
重做我的数据结构后,我想从不同的集合中嵌入一个文档(或其中的一部分)。注意 event.tags[]。目前,只存储了他们的字符串化 _id(作为纯字符串,没有 ObjectId!),但我想迁移他们的内容,比如{tags.name, tags._id}。我想用tag-documents 的内容更新/替换原来的event.tags。
数据
收集“事件”
db.events.insertMany([{
"_id" : ObjectId("5f6c5b0594911c0b7231643d"),
"title" : "Test Event",
"tags" : [
"5fd8cef2368c625a9d7516cb"
]
},
{
"_id" : ObjectId("5fb3896afc13ae2ed1000000"),
"title" : "Test Event 2",
"tags" : [
"5fd8cef2368c625a9d7516cb",
"5fd8cfb04a4a6063ab4ca4bf",
"5fd8cfb04a4a6063ab4ca4c0"
]
}
]);
集合“标签”
db.tags.insertMany([{
"_id" : ObjectId("5fd8cef2368c625a9d7516cb"),
"name" : "Foo",
"createdAt" : ISODate("2020-12-15T14:57:54.096Z")
},
{
"_id" : ObjectId("5fd8cfb04a4a6063ab4ca4bf"),
"name" : "Bar",
"createdBy" : "embo@team-con.de",
"createdAt" : ISODate("2020-12-16T14:57:54.096Z")
},
{
"_id" : ObjectId("5fd8cfb04a4a6063ab4ca4c0"),
"name" : "Foobar",
"createdAt" : ISODate("2020-12-17T14:57:54.096Z")
}
]);
预期结果
我想实现嵌入 "tags" 与 "events.tags" "tags._id" 匹配的集合的一些/所有字段 作为嵌入/嵌套文档的数组。这将是迁移脚本的一部分,在 mongoDB API >4.0 thru node.js 上运行。
目标:我想用不同集合的某些信息(参见集合标签)替换字符串数组(参见集合事件)并将其保存回集合事件(迁移过程)。所以我假设,我必须从tag 集合中获取/查找一些东西,并且需要一种机制来用复杂对象({tags._id,tags.name})替换字符串(events.tags[x])
{
"_id" : ObjectId("5f6c5b0594911c0b7231643d"),
"title" : "Test Event",
"tags" : [{
"_id" : ObjectId("5fd8cef2368c625a9d7516cb"),
"name" : "Foo",
"createdAt" : ISODate("2020-12-15T14:57:54.096Z")
}]
},
{
"_id" : ObjectId("5fb3896afc13ae2ed1000000"),
"title" : "Test Event 2",
"tags" : [{
"_id" : ObjectId("5fd8cef2368c625a9d7516cb"),
"name" : "Foo"
},
{
"_id" : ObjectId("5fd8cfb04a4a6063ab4ca4bf"),
"name" : "Bar"
},
{
"_id" : ObjectId("5fd8cfb04a4a6063ab4ca4c0"),
"name" : "Foobar"
}]
}
婴儿步
我尝试使用聚合管道,并在最后一步中将其内容匹配并查找到replaceWith。我不太熟悉通过聚合管道解决这个问题。
db.getCollection('events').aggregate([
{ $match: { tags: { "$exists" : true } } },
{
$lookup:
{
from: "tags",
localField: "tags",
foreignField: "_id",
as: "taags"
}
},
])
【问题讨论】:
标签: mongodb mongoose aggregation-framework