所以我正在開發一個應用程式,其中有兩個模型:帖子和類別。在帖子中有一個參考類別模型的欄位。現在有多個帖子具有相同的類別,我需要通過傳遞一個與類別名稱匹配的字串來獲取這些帖子。我需要在這里使用聚合,因為有數千個帖子。獲取90k個帖子,然后匹配類別名稱以查找所有帖子需要花費大量時間。所以我想使用聚合來查找具有類別名稱的類別,然后使用該類別的 id 來查找所有帖子。
假設這里有兩個模式:
**POSTS SCHEMA**
const postSchema = new mongoose.Schema( {
text: {
type: String
},
categories: [ {
_id: false,
categoryID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Categories',
}
} ]
} );
**CATEGORIES SCHEMA**
const categorySchema = new mongoose.Schema( {
category: {
type: String,
}
} );
所以現在假設我需要找到所有具有名為Politics. 我無法獲取所有帖子,然后根據類別名稱過濾掉,因為由于帖子總數,獲取需要很多時間。所以這是我嘗試過的:
const aggregateObj = [
{
"$lookup": {
"from": "categories",
"let": {
"category": "$category"
},
"pipeline": [
{
"$match": {
"category": "Politics"
}
}
],
"as": "category"
}
},
{
$unwind: "$category"
},
{
"$lookup": {
"from": "posts",
"pipeline": [
{
"$match": {
"categories.categoryID": "$_id"
}
}
],
"as": "posts"
}
}
];
const posts= await Post.aggregate( aggregateObj ).exec();
我沒有得到任何輸出,因為它繼續加載而沒有任何錯誤。我在這里做錯了什么?
uj5u.com熱心網友回復:
您不需要查找另一個集合然后使用它來查找另一個集合中的資料。您可以填充帖子集合,然后與您想要的字串匹配。像這樣的東西:
const aggregateObj = [
{
'$lookup': {
'from': 'categories',
'localField': 'categories.categoryID',
'foreignField': '_id',
'as': 'categories' // if you have a field with the same name then it will overwrite that and populate. Or you can just specify a different name
}
}, {
'$match': {
'categories.category': 'Politics'
}
}
];
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359649.html
