gpt4 book ai didi

node.js - MongoDB - 如何从具有 ID 的对象数组中检索多个集合

转载 作者:可可西里 更新时间:2023-11-01 10:08:47 24 4
gpt4 key购买 nike

所以,我有一个包含以下集合的数据库。

(使用整数表示对象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,我想返回为该客户推荐的书籍,并附加可能性给他们。

即:

desiredResult = [
{
_id: 1,
title: "Harry Potter",
likelihood: 0.9
},
{
_id: 2,
title: "The maze Potter",
likelihood: 0.8
}
...
]

请问,实现此目的的 MongoDB 聚合查询是什么?

最佳答案

您可以使用下面的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"
]
}
}}
])

关于node.js - MongoDB - 如何从具有 ID 的对象数组中检索多个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com