本書模型是:
const BookSchema = new Schema(
{
title: { type: String, required: true },
author_id: { type: Schema.Types.ObjectId, ref: 'User' },
summary: { type: String, required: true },
isbn: { type: String },
genre: [{ type: String, required: true }],
doc: {},
img: { type: String },
review_id: [{ type: Schema.Types.ObjectId, ref: 'Review' }],
pub_date: { type: Date, required: true },
totalRating: { type: Number, default: 0},
ratingCount: { type: Number, default: 0 },
hotRank: { type: Number, default: 0 },
popRank: { type: Number, default: 0 }
}
);
現在,我正在嘗試進行一個 mongodb 查詢,該查詢通過它的 id 查找書籍,并在同一查詢中通過流派標簽比較找到類似的對應物,例如:
db.books.aggregate(
[
{ $match: { _id: `book_id` } }, {
$addFields: {
"count": {
$size: {
$setIntersection: ["$genre", `founded_book_genre_tag`]
}
}
}
}, {
$sort: {
"count": -1
}
}, {
$project: { _id: 1, title: 1 }
}
])
注意:標簽匹配部分有效我只是想了解如何使用從管道的一個階段到其他階段的欄位參考。
編輯:
考慮檔案:
[
{
"_id": 1,"title": "sample1","genre": ["Sports","War","Fantasy"]
},
{
"_id": 2,"title": "sample2","genre": ["Fantasy","Games","War"]
},
{
"_id": 3,"title": "sample3","genre": ["Fantasy","Games","Sports","War"]
},
{
"_id": 4, "title": "sample4","genre": ["Games", "Fantasy","War","Action","Urban"]
},
{
"_id": 5, "title": "sample5","genre": ["History","Fantasy","Mystery","War"]
}
]
所以,如果我搜索 ID 為 2 的檔案,那么我應該推薦 ID 為 3 和 4 的書
如果使用 id 2 搜索書籍,輸出應該是這樣的:
{
_id: 2,
title: "sample2",
genre: ["Fantasy","Games","War"],
recd: [
{_id:3}, {_id: 4}
]
}
uj5u.com熱心網友回復:
一種選擇是:
db.collection.aggregate([
{$match: {_id: 2}},
{$lookup: {
from: "collection",
let: {genre: "$genre"},
pipeline: [
{$match: {$expr: {$eq: [{$setIsSubset: ["$$genre", "$genre"]}, true]}}},
{$project: {_id: 1}},
{$match: {_id: {$ne: 2}}}
],
as: "recd"
}
}
])
在playground 示例中查看它是如何作業的
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535909.html
標籤:数据库聚合
