首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在猫鼬$lookup后基于对象字段过滤查询

如何在猫鼬$lookup后基于对象字段过滤查询
EN

Stack Overflow用户
提问于 2022-06-05 04:22:25
回答 1查看 308关注 0票数 1

我想得到一个博客的评论按顶部(率)的评论模式排序:

代码语言:javascript
复制
const CommentSchema = new Schema({
    content: {type: String, maxLength: 100, required: true},
    user: {type: Schema.Types.ObjectId, ref: 'User', required: true },
    blog: {type: Schema.Types.ObjectId, ref: 'Blog', required: true},
    reactions: [{type: Schema.Types.ObjectId, ref: 'Reaction'}],
},{ timestamps: true})

const ReactionSchema = new Schema({
    user: {type: Schema.Types.ObjectId, ref: 'User', required: true},
    comment: {type: Schema.Types.ObjectId, ref: 'Comment', required: true},
    date: {type: Schema.Types.Date, default: Date.now, required: true}
})

我的问题是:

代码语言:javascript
复制
this.model.Reaction.aggregate([            
        {
          $group: {
            _id: "$comment",
            num: { $sum: 1 }
          }
        },
        { $sort: { num: -1 } },
        {
          $lookup: {
            from: "comments",
            localField: "_id",
            foreignField: "_id",
            as: "Com",
          }
        },
        { $unwind: "$Com" },
        {
            $match: {"Com.blog": '629af177e03ab4cfe845a9a4'}
        },
        {
          $project: {
            content: "$Com.content",
            num: 1,
          }
        },
      ])

但是$match在$lookup之后是不接受的!我也尝试使用"$filter“,但是它得到了一个”数组“和一个有一个对象!我的查询不需要$match。但是需要基于blog-id对评论进行过滤。

EN

回答 1

Stack Overflow用户

发布于 2022-06-05 15:51:32

你能试试这个吗

代码语言:javascript
复制
this.model.Reaction.aggregate([            
    {
      $group: {
        _id: "$comment",
        num: { $sum: 1 }
      }
    },
    { $sort: { num: -1 } },
    {
      $lookup: {
        from: "comments",
        localField: "_id",
        foreignField: "_id",
        as: "Com",
      }
    },
    { $unwind: "$Com" },
    {
        $match: {"Com.blog": mongoose.Types.ObjectId('629af177e03ab4cfe845a9a4')}
    },
    {
      $project: {
        content: "$Com.content",
        num: 1,
      }
    },
  ])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72504771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档