我有一个包含如下数据的数据库:
[{
"_id": {
"$oid": "664baf560b9539e48fbc6ed1"
},
"name": "first assignment",
"next": {
"$oid": "664baf620b9539e48fbc6ed2"
},
"preview": null,
"date": {
"$date": "2024-04-20T10:00:00.000Z"
}
},
{
"_id": {
"$oid": "664baf620b9539e48fbc6ed2"
},
"name": "second assignment",
"next": {
"$oid": "664baf6d0b9539e48fbc6ed3"
},
"preview": {
"$oid": "664baf560b9539e48fbc6ed1"
},
"date": {
"$date": "2024-04-21T10:00:00.000Z"
}
},
{
"_id": {
"$oid": "664baf6d0b9539e48fbc6ed3"
},
"name": "third assignment",
"next": {
"$oid": "664baf8d0b9539e48fbc6ed4"
},
"preview": {
"$oid": "664baf620b9539e48fbc6ed2"
},
"date": {
"$date": "2024-04-22T10:00:00.000Z"
}
},
{
"_id": {
"$oid": "664baf8d0b9539e48fbc6ed4"
},
"name": "fourth assignment",
"next": null,
"preview": {
"$oid": "664baf6d0b9539e48fbc6ed3"
},
"date": {
"$date": "2024-04-23T10:00:00.000Z"
}
}
]
下一个和预览字段引用同一集合中的其他文档。 因此,假设我收到第四个作业的 ID (664baf8d0b9539e48fbc6ed4)。我需要创建一个具有相同结构的新文档,其中预览是第四个作业的 ID,但还要更新第四个作业文档以将新创建的文档的 ID 分配给下一个。 此流程可以在聚合中实现吗?还是应该单独使用传统操作?
如果您在收到第 4 次作业的 id 时可以推断出第 5 次作业的内容,您可以
$set
第 4 次作业的 next
字段和 $unionWith
您在 $documents
阶段的第 5 次作业。最后执行 $merge
将 2 个文档更新到集合中。
db.collection.aggregate([
{
"$match": {
// id of 4th assignment
"_id": {
"$oid": "664baf8d0b9539e48fbc6ed4"
}
}
},
{
$set: {
next: {
// id of 5th assignment
"$oid": "664baf8d0b9539e48fbc6ed5"
}
}
},
{
"$unionWith": {
"coll": "collection",
"pipeline": [
{
"$documents": [
// 5th assignment here
{
"_id": {
"$oid": "664baf8d0b9539e48fbc6ed5"
},
"name": "fifth assignment",
"next": null,
"preview": {
// id of 4th assignment
"$oid": "664baf8d0b9539e48fbc6ed4"
},
"date": "$$NOW"
}
]
}
]
}
},
{
"$merge": {
"into": "collection",
"on": "_id"
}
}
])