[英]MongoDB - How to retrieve multiple collections from an array of objects that have their IDs
所以,我有一個包含以下集合的數據庫。
(使用整數表示對象 ID)
圖書:
books = [
{ _id: 1, title: "Harry Potter" },
{ _id: 2, title: "The maze runner" }
...
]
顧客:
customers = [
{ _id: 1, name: "John" },
{ _id: 2, title: "Jane"}
...
]
建議:
recommendations = [
{
customerID: 1,
recommendations: [
{ bookID: 1, likelihood: 0.9 },
{ bookID: 2, likelihood: 0.8 }
]
},
{
customerID: 2,
recommendations: [
{ bookID: 2, likelihood: 0.9 },
{ bookID: 1, likelihood: 0.8 }
]
}
...
]
現在,當請求發送到我的服務器時,在req.body
包含customerID
,我想為該客戶返回推薦的書籍,並附加可能性。
IE :
desiredResult = [
{
_id: 1,
title: "Harry Potter",
likelihood: 0.9
},
{
_id: 2,
title: "The maze Potter",
likelihood: 0.8
}
...
]
請問,實現此目的的 MongoDB 聚合查詢是什么?
下面的聚合可以幫助你
db.recommendations.aggregate([
{ $match: { "customerID": 1 } },
{ $unwind: "$recommendations" },
{ $lookup: {
from: "books",
localField: "recommendations.bookID",
foreignField: "_id",
as: "recomndedBook"
}},
{
$addFields: {
title: { $arrayElemAt: [ "$recomndedBook.title", 0 ] },
likelihood: "$recommendations.likelihood",
bookID: "$recommendations.bookID"
}
},
{
$project: {
recommendations: 0,
recomndedBook: 0,
_id: 0,
}
}
])
您可以使用以下aggregation
db.recommendations.aggregate([
{ "$match": { "customerID": 1 }},
{ "$unwind": "$recommendations" },
{ "$lookup": {
"from": "books",
"localField": "recommendations.bookID",
"foreignField": "_id",
"as": "recomndedBook"
}},
{ "$replaceRoot": {
"newRoot": {
"$mergeObjects": [
{ "$arrayElemAt": ["$recomndedBook", 0] },
"$recommendations"
]
}
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.