【问题标题】:MongoDB: sort, but with with a specific document first in the results?MongoDB:排序,但在结果中首先使用特定文档?
【发布时间】:2019-06-16 11:16:05
【问题描述】:

MGMT 和 sales 设置的要求当然是查询结果应包含特定文档作为第一个结果,然后是与查询匹配的所有其他文档。

这是我的数据的一个非常简化的示例:

{ _id: 1,
title: 'other item',
category: 'show'
}
{ _id: 2,
title: 'THE ITEM THAT MUST BE RETURNED FIRST',
category: 'show'
}
{ _id: 3,
title: 'other item 2',
category: 'show'
}
{ _id: 4,
title: 'item not matching query',
category: 'hide'
}

在这个例子中,我在 http 请求正文中传递了一个值 id{ _id : 2 },我需要查询符合某些条件的所有其他文档,在这个例子中是 { category: 'show' },但是文章id == 2 需要是第一个返回的文档:

//pseudo-code. I know this is not even close
itemsCollection.aggregate([
{ $match : { category: 'show'} }
// sort, but with item with id == 2 at top, and the rest sorted by title ASC
{ $sort : { {item_with_id_2: first_returned }, {title: 1} }
])

以上是我需要的结果的伪代码:

{ _id: 2,
title: 'THE ITEM THAT MUST BE RETURNED FIRST',
category: 'show'
}
{ _id: 1,
title: 'other item',
category: 'show'
}
{ _id: 3,
title: 'other item 2',
category: 'show'
}

如何强制将一个特定文档(我确实拥有其 id)置于查询结果的顶部?

【问题讨论】:

  • 您最终可以在聚合早期阶段尝试添加一个预定义字段(“sort_key”),其 _id 值为 0:其余部分为 2 和 1 ...然后继续使用它用于以您想要的方式对值进行排序。我猜这不是很好,但它确实有用。也许这会有所帮助:docs.mongodb.com/manual/reference/operator/aggregation/…

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您可以尝试以下方法:

itemsCollection.aggregate([
  {
    "$project": {
      "_id": 1,
      "category": 1,
      "title": 1,
      "priority": {
        "$eq": [
          "$_id",
          2
        ]
      }
    }
  },
  {
    "$sort": {
      "priority": -1
    }
  }
])

本质上,我们正在创建一个合成属性priority,当_id 匹配时,它被设置为true。最后,我们按priority 排序以返回匹配项 - 与_id 匹配的文档将位于顶部,然后是其余文档。

【讨论】:

  • 这是我需要的。对于事后研究此问题的任何人:"priority" : { "$eq" : ["$_id", item_id] } 是解决问题的部分。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2012-12-15
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2014-05-10
相关资源
最近更新 更多