更新时间:2023-12-03 16:27:16
您可以运行带有条件、投影和排序的常规查找查询.我认为您想对不想投影的字段进行排序.不过不用担心,即使没有投影,您也可以在该字段上进行排序.
You can run a usual find query with conditions, projections, and sort. I think you want to sort on a field that you don't want to project. But don't worry about that, you can sort on that field even after not projecting it.
如果您明确选择排序字段的投影为0",那么您将无法执行该查找查询.
If you explicitly select projection of sorting field as "0", then you won't be able to perform that find query.
//This query will work
db.collection.find(
{_id:'someId'},
{'someField':1})
.sort('someOtherField':1)
//This query won't work
db.collection.find(
{_id:'someId'},
{'someField':1,'someOtherField':0})
.sort('someOtherField':1)
但是,如果您仍然没有得到所需的结果,请查看 MongoDB 聚合框架!
However, if you still don't get required results, look into the MongoDB Aggregation Framework!
这是根据您的要求进行聚合的示例查询
Here is the sample query for aggregation according to your requirement
db.collection.aggregate([
{$match: {_id:'someId'}},
{$sort: {someField:1}},
{$project: {_id:1,someOtherField:1}},
])