【发布时间】: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