我有这样的数据库收集:
{
"_id" : "af5c00e4-d3a8-419d-8793-c0cf328802ec",
"collaborators" : [
{
"_id" : "9bd2eee8-bf6c-4c6f-bab7-d2d175aed807",
"origin" : [
{
"originId" : "123"
}
],
"firstName" : "Parveen",
"lastName" : "Vendor",
"email" : "pk@gmail.com"
},
{
"_id" : "234324-bf6c-4c6f-bab7-d2d175aed807",
"origin" : [
{
"originId" : "1234"
}
],
"firstName" : "Parveen123",
"lastName" : "34",
"email" : "abc@gmail.com"
}
],
"orders" : [
{
"totalAmount" : 10,
"collaborators" : [
{
"origin" : [
{
"originId" : "123",
}
],
"type" : "Supplier"
},
{
"origin" : [
{
"originId" : "1233",
}
],
"type" : "Supplier"
}
]
}
]
}
要替换orders (array) collaborators(array)中的数据
**合作者(数组)**数据如果匹配两个
预期输出
{
"_id" : "af5c00e4-d3a8-419d-8793-c0cf328802ec",
"collaborators" : [
{
"_id" : "9bd2eee8-bf6c-4c6f-bab7-d2d175aed807",
"origin" : [
{
"originId" : "123"
}
],
"firstName" : "Parveen",
"lastName" : "Vendor",
"email" : "pk@gmail.com"
},
{
"_id" : "234324-bf6c-4c6f-bab7-d2d175aed807",
"origin" : [
{
"originId" : "1234"
}
],
"firstName" : "Parveen123",
"lastName" : "34",
"email" : "abc@gmail.com"
}
],
"orders" : [
{
"totalAmount" : 10,
"collaborators" : [
{
"_id" : "9bd2eee8-bf6c-4c6f-bab7-d2d175aed807",
"origin" : [
{
"originId" : "123"
}
],
"firstName" : "Parveen",
"lastName" : "Vendor",
"email" : "pk@gmail.com"
},
{
"origin" : [
{
"originId" : "1233",
}
],
"type" : "Supplier"
}
]
}
]
}
一个收集记录可以有多个合作者,就像订单可以有多个合作者一样。只需要替换originId匹配
的地方一个选项是:
- 使用
$map
,$mergeObjects
和$filter
为orders.collaborators
的每一项添加一个new
键,如果存在collaborators
的匹配项 - 如果包含数据则选择
new
键,如果不包含数据则选择original
键。
db.collection.aggregate([
{$set: {
ordersCollaborators: {
$map: {
input: {$first: "$orders.collaborators"},
in: {$mergeObjects: [
{original: "$$this"},
{new: {
$filter: {
input: "$collaborators",
as: "i",
cond: {
$eq: [
{$first: "$$i.origin.originId"},
{$first: "$$this.origin.originId"}
]
}
}
}
}
]
}
}
}
}
},
{$set: {
orders: [
{totalAmount: {$first: "$orders.totalAmount"},
collaborators: {
$map: {
input: "$ordersCollaborators",
in: {
$cond: [
{$eq: [{$size: "$$this.new"}, 0]},
"$$this.original",
"$$this.new"
]
}
}
}
}
],
ordersCollaborators: "$$REMOVE"
}
}
])
看看它在操场的例子中是如何工作的