查找 Objects 数组
lookup on array of Objects
如何通过引用 ID 和其他属性使用 object 进行查找。
集合A
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: "A1",
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
]
}
收藏B
{
_id: ObjectId("6013859ba0c3120034d08bfb"),
name: "B1"
}
{
_id: ObjectId("6013859ba0c3120034d08bfc"),
name: "B2"
}
预期结果
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: 'A1',
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), name: "B1", text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), name: "B2", text: "DEF"}
]
}
$unwind
- 解构 refs
数组字段。
$lookup
- 加入 collectionA
(refs.id
) 与 collectionB
(_id
).
$project
- 修饰文档,通过 $first
. 从 refsB
数组中获取名字
$group
- 按 _id
分组并为文档生成(必填)字段。
db.collectionA.aggregate([
{
$unwind: "$refs"
},
{
"$lookup": {
"from": "collectionB",
"localField": "refs.id",
"foreignField": "_id",
"as": "refsB"
}
},
{
$project: {
_id: 1,
name: 1,
refs: {
id: "$refs.id",
text: "$refs.text",
name: {
$first: "$refsB.name"
}
}
}
},
{
$group: {
_id: "$_id",
name: {
$first: "$name"
},
refs: {
$push: "$refs"
}
}
}
])
如何通过引用 ID 和其他属性使用 object 进行查找。
集合A
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: "A1",
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
]
}
收藏B
{
_id: ObjectId("6013859ba0c3120034d08bfb"),
name: "B1"
}
{
_id: ObjectId("6013859ba0c3120034d08bfc"),
name: "B2"
}
预期结果
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: 'A1',
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), name: "B1", text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), name: "B2", text: "DEF"}
]
}
$unwind
- 解构refs
数组字段。$lookup
- 加入collectionA
(refs.id
) 与collectionB
(_id
).$project
- 修饰文档,通过$first
. 从 $group
- 按_id
分组并为文档生成(必填)字段。
refsB
数组中获取名字
db.collectionA.aggregate([
{
$unwind: "$refs"
},
{
"$lookup": {
"from": "collectionB",
"localField": "refs.id",
"foreignField": "_id",
"as": "refsB"
}
},
{
$project: {
_id: 1,
name: 1,
refs: {
id: "$refs.id",
text: "$refs.text",
name: {
$first: "$refsB.name"
}
}
}
},
{
$group: {
_id: "$_id",
name: {
$first: "$name"
},
refs: {
$push: "$refs"
}
}
}
])