【发布时间】:2022-01-02 09:29:45
【问题描述】:
我有 3 个模型:
- 学习
- 词集
- 类别
学习模型引用了WordSet,然后WordSet引用了Category。
我知道为了正常显示数据,我使用填充。
但在这种情况下,我需要一个包含许多 $lookup 的查询。
如何从 WordSet 中“填充”类别并仅显示重复次数最多的类别?
我会得到这样的回应:
"stats": [
{
"_id": null,
"numberOfStudies": 4,
"averageStudyTime": 82.5,
"allStudyTime": 330,
"longestStudy": 120,
"allLearnedWords": 8
"hardestCategory": "Work" // only this field is missing
}
]
我试过这样做:
const stats = await Study.aggregate([
{
// join User table
$lookup: {
from: 'User',
let: { userId: '$user' },
pipeline: [
{
$match: { $expr: { $eq: ['$_id', '$$userId'] } },
},
],
as: 'currentUser',
},
},
{
// join WordSet table
$lookup: {
from: 'WordSet',
let: { wordSetId: '$learnedWordSet' },
pipeline: [
{
$match: { $expr: { $eq: ['$_id', '$$wordSetId'] } },
},
{
// from this moment i'm not sure how to make it work
$lookup: {
from: 'Category',
let: { categoryId: '$category' },
pipeline: [
{
$match: { $expr: { $in: ['$_id', '$$categoryId'] } },
},
],
as: 'category',
},
},
],
as: 'wordSet',
},
},
{ // add wordset with category? this is not working
$addFields: {
wordSet: {
$arrayElemAt: ['$wordSet', 0],
},
},
},
{ // search by logged user
$match: { user: new ObjectID(currentUserId) },
},
{
$group: {
// display statistics about user's studying
_id: null,
numberOfStudies: { $sum: 1 },
averageStudyTime: { $avg: '$studyTime' },
allStudyTime: { $sum: '$studyTime' },
longestStudy: { $max: '$studyTime' },
allLearnedWords: { $sum: { $size: '$learnedWords' } },
// category: check which category is repeated the most and display it
},
},
]);
学习
const studySchema = new mongoose.Schema({
name: {
type: String,
},
studyTime: {
type: Number,
},
learnedWords: [String],
notLearnedWords: [String],
learnedWordSet: {
type: mongoose.Schema.Types.ObjectId,
ref: 'WordSet',
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
});
单词集
const wordSetSchema = new mongoose.Schema({
name: {
type: String,
},
category: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
required: true,
},
],
},
});
类别
const categorySchema = new mongoose.Schema({
name: {
type: String,
},
});
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework mongoose-populate