【问题标题】:How to sort mongodb find results by the length of a string property? [duplicate]如何按字符串属性的长度对mongodb查找结果进行排序? [复制]
【发布时间】:2018-09-28 23:01:00
【问题描述】:

我想按特定字符串属性的长度对查找结果进行排序。我的架构有一个子属性“评论”,我想按评论的长度排序。 我正在运行类似这样的查找查询。

Model.find(query, callback)
.sort({ 'review.comment.length' : -1 })

架构:

feedback = new Schema({
    review: {type: content}
})


content = new Schema({
   comment: {type: String},
   date: {type: Date}
})

但这不起作用。有人可以帮助进行正确的查询吗?

【问题讨论】:

  • 你能分享你的架构吗?
  • @GeorgeBailey 添加了架构的相关部分。

标签: javascript node.js mongodb mongoose


【解决方案1】:

您可以为此使用aggregate 框架和$strLenCP

有点像

db.collection.aggregate(
 [
  {
    {$match : {property : 'value'}} //This is your filter criteria
     $project: {

        length: { $strLenCP: "$review.comment" }
     }
  },
   {$sort:{length: -1}}
 ]
)

【讨论】:

  • 但我正在使用查找。如何在这里适应聚合框架?抱歉,MongoDB 世界的新手。
  • 无需容纳。它已经在那里了。首先在 mongo shell 上尝试这个查询
  • 告诉我结果是什么
  • 我的意思是如何同时使用查找和聚合?
  • 哦。您可以使用{$match : {property : "value'}} 管道进行过滤。这就像 find 中的过滤器
猜你喜欢
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2014-02-13
相关资源
最近更新 更多