在
MongoDB
中,可以使用
$lookup
和
$addFields
来实现将一个集合中的字段复制到另一个集合中。
假设有两个集合:
collection1
和
collection2
,我们要将
collection1
中的字段
field1
复制到
collection2
中。
首先,我们可以使用
$lookup
将
collection1
和
collection2
进行关联,并获取匹配的文档:
db.collection2.aggregate([
$lookup: {
from: "collection1",
localField: "field2",
foreignField: "_id",
as: "matching_docs"
在这里,localField
是collection2
中的字段,foreignField
是collection1
中的字段,as
定义了匹配的文档在collection2
中的字段名。
接下来,我们可以使用$addFields
将field1
复制到collection2
中:
db.collection2.aggregate([
$lookup: {
from: "collection1",
localField: "field2",
foreignField: "_id",
as: "matching_docs"
$addFields: {
field1: { $arrayElemAt: ["$matching_docs.field1", 0] }
在这里,$arrayElemAt
用于获取matching_docs
数组中的第一个元素的field1
值,并将其赋值给field1
字段。
完整的代码示例:
db.collection2.aggregate([
$lookup: {
from: "collection1",
localField: "field2",
foreignField: "_id",
as: "matching_docs"
$addFields: {
field1: { $arrayElemAt: ["$matching_docs.field1", 0] }
请注意,这里假设field2
是collection2
中的字段,它与collection1
中的_id
字段进行关联。您可以根据实际情况调整这些字段。