[英]How can I combine two collections in MongoDB depending on different IDs?
我想加入MongoDB的兩個collections。 如果 _id 和 creatorId 匹配,我想加入他們。 這就是我所做的。
User.aggregate([
{
$lookup:
{
from: "traveladds",
let: { personalId: "$_id"},
pipeline: [
{ $match:
{ $expr:
[
{ $eq: [ "$creatorId", "$$personalId" ] },
]
}
}
],
as: "stockdata"
}
},
]).exec((err, result) => {
if(err){
res.send(err)
}
if(result){
res.send({
error: false,
data: result,
})
}
})
但是當我這樣做時, traveladds -collection 中的所有文檔都存儲在所有用戶的 stockdata 中。
用戶收藏:
"_id": "609bc1b9bbc4ff184194c20f",
"homeCountry": "",
"birthdate": "",
"email": "",
"password": "",
"firstName": "",
"lastName": "",
"__v": 0,
"about": "",
"gender": "",
Traveladds 集合:
"{
"_id": "609bc1fdbbc4ff184194c210",
"title": "",
"destination": "",
"description": "",
"minbudget": ,
"maxbudget": ,
"startdate": "",
"enddate": "",
"creatorId": "609bc1b9bbc4ff184194c20f",
"creatorName": "",
"createdAt": "",
"updatedAt": "",
"__v": 0
},
這是結果:
data": [
{
"_id": "609bc1b9bbc4ff184194c20f",
"homeCountry": "",
"birthdate": "",
"email": "",
"password": "",
"firstName": "",
"lastName": "",
"__v": 0,
"about": "",
"gender": "",
"stockdata": [
{
"_id": "609bc1fdbbc4ff184194c210",
"title": "",
"destination": "",
"description": "",
"minbudget": ,
"maxbudget": ,
"startdate": "",
"enddate": "",
"creatorId": "609bc1b9bbc4ff184194c20f",
"creatorName": "",
"createdAt": "",
"updatedAt": "",
"__v": 0
},
{
"_id": "609eb5f401c77217984e4a78",
"title": "",
"destination": "",
"description": "",
"minbudget": ,
"maxbudget": ,
"startdate": "",
"enddate": "",
"creatorId": "609e9bb378336c21581cd132",
"creatorName": "",
"createdAt": "",
"updatedAt": "",
"__v": 0
},
{
"_id": "60a216cfd43c8e1e375cf0a8",
"title": "",
"destination": "",
"description": "",
"minbudget": ,
"maxbudget": ,
"startdate": "",
"enddate": "",
"creatorId": "609e39572c60480de0fd6ef1",
"creatorName": "",
"createdAt": "",
"updatedAt": "",
"__v": 0
},
]
},
如您所見,即使有 creatorId.= _id 它顯示在 stockdata 中。 並且所有這三個都出現在所有用戶中。
有人可以為我提供任何想法嗎? 提前致謝,祝您有美好的一天。
更新:這與下面的答案結合使用!
個人ID:{$toString:“$_id”}
您已編寫正確的查詢。 但是有一些不必要的括號
db.User.aggregate([
{
$lookup: {
from: "traveladds",
let: {
personalId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$creatorId",
"$$personalId"
]
}
}
}
],
as: "stockdata"
}
},
])
工作Mongo游樂場
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.