让我们说我有3个模式
让我们说一个模式是
// 1 house 1 schema
const HouseSchema = Schema({
state: Number,
houseNumber: String,
houseImage: String,
houseAge: Number,
});
const FamilySchema = Schema({
house: {
type: Schema.Types.ObjectId,
ref: "house"
},
fullName: String,
gender: String
});
const EducationSchema = new Schema({
family: {
type: Schema.Types.ObjectId,
ref: "familydetail"
},
educationLevel: String,
educationFinishedYear: Number
});
我想要这样一种结果,即所有按性别划分的家庭成员都生活在州:1 (ref: house)
,结果组按educationLevel
居住。
我通过使用填充和匹配功能(例如:
)简单地完成了此操作const getEducationCount = async (education, sex, ward) => {
try {
let edu = await Education.find(education, "family").populate({
path: "family",
match: sex,
select: "house",
populate: {
path: "house",
match: ward,
select: "_id"
}
});
if (edu) {
// console.log("education", edu);
let count =
(await edu.filter(
each => !isEmpty(each.family) && !isEmpty(each.family.house)
).length) || 0;
// console.log(count);
return count;
}
} catch (error) {
console.log(error);
}
};
我必须为每个educationlevel
调用此函数,这需要很长时间。
它始终扫描n number of documents
。如何优化呢?
我该怎么做:
Education.aggregate([
{
$match: {}
},
{
$group: {
_id: "$educationLevel",
},
},
{
$lookup: {
from: "family",
localField: "family",
foreignField: "_id",
as: "family",
$group: {
_id: "$gender",
},
$lookup: {
from: "house",
localField: "house",
foreignField: "_id",
as: "house",
$match: {
state: 1,
}
}
}
}
])
任何参考和提示将不胜感激。
谢谢。