【问题标题】:Sort docs by array length in Mongoose在 Mongoose 中按数组长度对文档进行排序
【发布时间】:2019-10-27 22:38:25
【问题描述】:

我有一个简单的帖子架构,其中包含喜欢此帖子的用户 ID 数组:

const PostSchema = new Schema({

title:{type: String, required: true},
content:    {type: String, required: true },
tags:       [{type:String}],
author:     {type:mongoose.Schema.Types.ObjectId, ref:"User", required:true},
likes:      [{ type:mongoose.Schema.Types.ObjectId, ref:"User", required:false}],
createTime: {type:Date, default:Date.now}

})

我想订购我的文档我的喜欢计数,换句话说,我的帖子按喜欢数组长度排序。我尝试了这样的事情,但它不起作用:

// @route  GET api/posts

router.get('/',(req, res)=>{

  Post.aggregate([{ $addFields: {likesCount:{$size:"likes"}} }]);
  Post.find()
    .populate('author','name email')
    .sort({likesCount:1})
    .then(posts=> res.json(posts))
    .catch(err=>console.log(err))
  })

我不知道如何正确地制作它。请任何帮助。提前谢谢你:)

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

    Post.aggregate([
      { "$lookup": {
        "from": Author.collection.name,
        "let": { "author": "$author" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$author" ] } } },
          { "$project": { "name": 1, "email": 1 }}
        ],
        "as": "author",
      }},
      { "$unwind": "$author" },
      { "$addFields": { "likesCount": { "$size": "$likes" }}},
      { "$sort": { "likesCount": 1 }}
    ])
    

    【讨论】:

    • 谢谢。对我来说似乎太难了。请告诉我如何使用聚合添加字段 likesCount。我想我可以写一些类似 Post.find().sort({likesCount:1}) 的东西,这对我来说会更容易理解
    • 它是一个聚合查询,与 find 相同,但主要用于重塑数据格式。所以我在这里使用了$lookup 而不是populate,并添加了一个字段likesCount,然后用它创建了$sort
    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2019-04-11
    • 2013-08-18
    • 2010-10-02
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多