合并一个数组中的两个对象,一个对象的键比另一个对象嵌套在 Mongo DB 中同一文档中的另一个对象更深
Merge two objects inside an array, one with a key nested deeper than the other in the same document in Mongo DB
文档的架构
id
是加入的关键
{
"foo" : [
{
"properties" : {
"id" : 1
},
},
{
"properties" : {
"id" : 2
},
}],
"bar" : [
{
"id" : 1,
"metadata" : abc
},
{
"id" : 2,
"metadata" : def
}
]
}
目标
{
"foo" : [
{
"properties" : {
"id" : 1,
"metadata" : abc
},
},
{
"properties" : {
"id" : 2,
"metadata" : def
},
},
}
您可以在模式上使用 $lookup,并在 $unwind 和 $project 的帮助下获得所需的结果。
查询:
db.foo.aggregate({
$lookup: {
from: "bar",
localField: "properties.id",
foreignField: "id",
as: "properties"
},
},
{
$unwind: {
path: "$properties",
}
},
{
$project: {
_id: 0,
properties: 1
}
})
输出:
[
{
"properties": {
"_id": ObjectId("5a934e000102030405000000"),
"id": 1,
"metadata": "abc"
}
},
{
"properties": {
"_id": ObjectId("5a934e000102030405000001"),
"id": 2,
"metadata": "def"
}
}
]
文档的架构
id
是加入的关键
{
"foo" : [
{
"properties" : {
"id" : 1
},
},
{
"properties" : {
"id" : 2
},
}],
"bar" : [
{
"id" : 1,
"metadata" : abc
},
{
"id" : 2,
"metadata" : def
}
]
}
目标
{
"foo" : [
{
"properties" : {
"id" : 1,
"metadata" : abc
},
},
{
"properties" : {
"id" : 2,
"metadata" : def
},
},
}
您可以在模式上使用 $lookup,并在 $unwind 和 $project 的帮助下获得所需的结果。
查询:
db.foo.aggregate({
$lookup: {
from: "bar",
localField: "properties.id",
foreignField: "id",
as: "properties"
},
},
{
$unwind: {
path: "$properties",
}
},
{
$project: {
_id: 0,
properties: 1
}
})
输出:
[
{
"properties": {
"_id": ObjectId("5a934e000102030405000000"),
"id": 1,
"metadata": "abc"
}
},
{
"properties": {
"_id": ObjectId("5a934e000102030405000001"),
"id": 2,
"metadata": "def"
}
}
]