【问题标题】:How to keep null values at the end of sorting in Mongoose? [duplicate]如何在 Mongoose 排序结束时保持空值? [复制]
【发布时间】:2018-11-23 04:42:07
【问题描述】:

我正在查询一个集合并根据一个属性对结果进行排序。有些文档还没有该属性值,即 null。在排序和限制(asc 或 desc)之后,我想在结果末尾保留具有空值的文档。 Mongoose 中是否有一种简单的方法可以使用单个查询来做到这一点? 如果没有,我如何分别使用两个查询,因为我必须限制结果以及分页?

var dealSchema = new Schema({

    // For Presentation Purposes Only
    dealId: { type: Number, index: true, unique: true },

    // BRAND Info
    brand: { type: ObjectId, ref: 'brand', index: true },
    brandUser: { type: ObjectId, ref: 'user', index: true, required: true },
    campaign: { type: ObjectId, ref: 'campaign', index: true },

    metrics: {
        totalCost: Number,
        totalValue: Number,
        roi: { type: Number, index: true },
        cpe: { type: Number, index: true }
    }

})

我想根据“metrics.cpe”按升序排序,但希望 null 或 0 值位于列表末尾。示例:

[0.1, 0.4, 0.7, 1.5, 2.5, 0, 0, null, null]

示例文档

{
  "_id": "590cdf29c102ae31208fa43a",
  "campaign": "587e6a880c844c6c2ea01563",
  "brand": "5a4cff5f8eaa1c26ca194acc",
  "brandUser": "57fd30cf0df04f1100153e07",
  "metrics": {
    "roi": 0,
    "cpe": 0,
    "totalValue": 0,
    "totalCost": 6000
  }
}

【问题讨论】:

  • @Ashish 已更新。谢谢
  • @Ashish 更新

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

我不确定我要说的解决方案。我无法对此进行测试,因为我现在没有设置 mongo db,但我认为您可以使用 <collection>.aggregate 以及 $project$sort 来实现这一点。

示例代码:

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$amount", -1*(<mimimum value>)* ] }
         }
      },
      { 
         $sort : { 
           amount : (-1 or 1 depending on the order you want)
         }
      }
   ]
)

希望这会有所帮助!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多