排序后如何在MongoDB中进行投影? [英] How to project in MongoDB after sort?

查看:41
本文介绍了排序后如何在MongoDB中进行投影?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

find 操作中的字段可以被排除,但是如果我想要做一个 find 然后一个 sort 和紧随其后的 <代码>投影.你知道什么技巧,操作吗?

In find operation fields can be excluded, but what if I want to do a find then a sort and just after then the projection. Do you know any trick, operation for it?

doc:fields {Object},要在查询中返回的字段.要包含或排除的字段对象(不能同时包含),{‘a’:1}

推荐答案

您可以运行带有条件、投影和排序的常规查找查询.我认为您想对不想投影的字段进行排序.不过不用担心,即使没有投影,您也可以在该字段上进行排序.

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}},
])

这篇关于排序后如何在MongoDB中进行投影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆