我有兩個系列。
顧客:
{
"_id" : ObjectId("584aac38686860d502929b8b"),
"name" : "user",
"email" : "[email protected]"
}
帖子:
{
"_id" : ObjectId("584aaca6686860d502929b8d"),
"title" : "Post",
"description":"description",
"user_id" : "584aac38686860d502929b8b"
}
我想根據 user_id(來自posts集合)- _id(在customers集合中)加入這個集合。
我嘗試了以下查詢:
dbo.collection('customers').aggregate([
{
$lookup:
{
from: 'posts',
localField: 'user_id',
foreignField: '_id',
as: 'posts'
}
}
])
但它不起作用。
我得到的輸出:
{
"_id": "584aac38686860d502929b8b",
"name": "user",
"email": "[email protected]",
"posts": []
}
uj5u.com熱心網友回復:
從附加的posts集合中,user_id是一個字串,但不是ObjectId。
要進行比較,您必須先轉換user_id為ObjectId。
db.customers.aggregate([
{
$lookup: {
from: "posts",
let: {
customerId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
{
"$toObjectId": "$user_id"
},
"$$customerId"
]
}
}
}
],
as: "posts"
}
}
])
示例 Mongo Playground
注意:從您現有的$lookup中,您已反轉localField和foreignField。
具有單連接條件的相等匹配
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/467804.html
