MongoDB:如何像MySQL中的fields关键字一样对结果中的记录进行排序

27 浏览
0 Comments

MongoDB:如何像MySQL中的fields关键字一样对结果中的记录进行排序

我想按照结果集中的记录进行排序。在MongoDB中,我该如何获得我预期的结果呢?在MySQL中,我可以使用以下查询来按照我期望的方式进行排序。

但是在MongoDB中,我应该如何做呢?

请给予指导。谢谢!

0
0 Comments

MongoDB does not provide a built-in way to order the records in the results like the "fields" keyword in MySQL. This difference in functionality has caused some confusion for users who are accustomed to using the "fields" keyword in MySQL.

To address this issue, one user suggests using the find() method in MongoDB with the projection parameter to specify the fields to include in the results. They provide an example code snippet:

db.users.find({},{_id:0,"accounts":1,"name":1});

However, it is mentioned that they have never tried ordering the fields in MongoDB using this method. Another user then expresses the desire to sort the results based on a specific order of IDs.

In conclusion, the issue arises from the difference in functionality between MongoDB and MySQL, where MongoDB lacks a direct way to order fields in the results. The suggested solution involves using the find() method with the projection parameter to specify the desired fields, but it is unclear whether this method can be used to order the fields as well.

0