MongoDB:排序,但在结果中首先使用特定文档?

Joh*_*uez 3 mongoose mongodb mongodb-query aggregation-framework

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

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

{ _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'
}
Run Code Online (Sandbox Code Playgroud)

在本例中,我在 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} }
])
Run Code Online (Sandbox Code Playgroud)

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

{ _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'
}
Run Code Online (Sandbox Code Playgroud)

如何强制将id我拥有的单个特定文档置于查询结果的顶部?

Mo *_*o A 5

您可以尝试以下操作:

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

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