我在很长一段时间后开始使用MongoDB,但我无法编写代码来执行以下操作。
我在这里要做的是从 suspects 和 lawyers 文档中执行查找,并将它们与
suspects
字段中的字段合并。
目前,我已经执行了单个查找操作,但无法将其与现有对象组合。
[
{
$unwind: "$suspects",
},
{
$lookup: {
from: "suspects",
let: {
suspectObjId: {
$toObjectId: "$suspects.id",
},
},
pipeline: [
{
$match: {
$expr: {
$eq: ["$_id", "$$suspectObjId"],
},
},
},
],
as: "suspects",
},
}
]
嫌疑人证件:
[
{
"_id": ObjectId("64f8d65249432809cdc3cb37"),
"fullName": "John Doe -1",
"phoneNumber": "XXXXXXXXX",
"totalCriminalRecord": 3
},
{
"_id": ObjectId("64f8d6cd49432809cdc3cb38"),
"fullName": "John Doe -2",
"phoneNumber": "XXXXXXXXX",
"totalCriminalRecord": 5
}
],
律师文件:
[
{
"_id": ObjectId("64f8d58849432809cdc3cb34"),
"fullName": "John Doe -3",
"phoneNumber": "XXXXXXXXX",
"workAddress": "Address of .."
},
{
"_id": ObjectId("64f8d5f349432809cdc3cb35"),
"fullName": "John Doe -4",
"phoneNumber": "XXXXXXXXX",
"workAddress": "Address of .."
}
],
案例文件:
[
{
"_id": ObjectId("64f8d9f549432809cdc3cb3d"),
"crimeNumber": 12345,
"eventDate": "01/01/2023",
"suspects": [
{
"id": "64f8d65249432809cdc3cb37",
"note": "-- additional note --",
"lawyer": {
"id": "64f8d58849432809cdc3cb34",
"note": "--additional note --"
}
}
]
}
]
我希望结果如下:
{
"_id": ObjectId("64f8d9f549432809cdc3cb3d"),
"crimeNumber": 12345,
"eventDate": "01/01/2023",
"suspects": [
{
"id": "64f8d65249432809cdc3cb37",
"fullName": "John Doe -1",
"phoneNumber": "XXXXXXXXX",
"totalCriminalRecord": 3,
"note": "-- additional note --",
"lawyer": {
"id": "64f8d58849432809cdc3cb34",
"fullName": "John Doe -3",
"phoneNumber": "XXXXXXXXX",
"workAddress": "Address of ..",
"note": "--additional note --"
}
}
]
}
你的方向是正确的。只需执行
$lookup
即可获取您需要的所有内容,然后使用 $mergeObjects
来争夺它们。
db.cases.aggregate([
{
"$unwind": "$suspects"
},
{
"$lookup": {
"from": "suspects",
"let": {
"suspectsIds": {
"$toObjectId": "$suspects.id"
}
},
"pipeline": [
{
"$match": {
$expr: {
"$eq": [
"$_id",
"$$suspectsIds"
]
}
}
},
{
"$unset": "_id"
}
],
"as": "suspectsLookup"
}
},
{
"$unwind": "$suspectsLookup"
},
{
"$lookup": {
"from": "lawyers",
"let": {
"lawyersIds": {
"$toObjectId": "$suspects.lawyer.id"
}
},
"pipeline": [
{
"$match": {
$expr: {
"$eq": [
"$_id",
"$$lawyersIds"
]
}
}
},
{
"$unset": "_id"
}
],
"as": "lawyersLookup"
}
},
{
"$unwind": "$lawyersLookup"
},
{
"$set": {
"suspects.lawyer": {
"$mergeObjects": [
"$suspects.lawyer",
"$lawyersLookup"
]
}
}
},
{
"$set": {
"suspects": [
{
"$mergeObjects": [
"$suspects",
"$suspectsLookup"
]
}
]
}
},
{
"$unset": [
"lawyersLookup",
"suspectsLookup"
]
}
])