mongodb排序
MongoDB sort method sorts the document in either ascending or descending order as specified by the user in the input argument.
MongoDB排序方法按照用户在输入参数中指定的升序或降序对文档进行排序。
MongoDB排序 (MongoDB sort)
The syntax for MongoDB sort method is:
MongoDB排序方法的语法为:
{ $sort:{<field1>:<sort order>........}}
sort order can take the following values:
排序顺序可以采用以下值:
1: specifies that the field should be sorted in ascending order
1:指定字段应按升序排序
-1: specifies that the field should be sorted in descending order
-1:指定字段应按降序排序
MongoDB排序示例 (MongoDB sort example)
Lets see an example for sorting the fields. Note that you can create the example data using MongoDB insert.
让我们看一个对字段排序的例子。 请注意,您可以使用MongoDB insert创建示例数据。
>db.car.find().sort({speed:-1})
{ "_id" : ObjectId("5471d72e0ce70a7026ebefee"), "name" : "Esteem", "color" : "JetRed", "cno" : "H414", "mfdcountry" : "Italy", "speed" : 65 }
{ "_id" : 3, "name" : "Alto", "color" : "Silver", "cno" : "H413", "mfdcountry" : "India", "speed" : 55 }
{ "_id" : 2, "name" : "Volkswagen", "color" : "Blue", "cno" : "H412", "mfdcountry" : "Japan", "speed" : 52 }
{ "_id" : 1, "name" : "Polo", "color" : "White", "cno" : "H411", "mfdcountry" : "Germany", "speed" : 45 }
Sorts the car collection documents in descending order for the speed field.
按速度字段的降序对汽车收集文档进行排序。
>db.car.find().sort({name:1})
{ "_id" : 3, "name" : "Alto", "color" : "Silver", "cno" : "H413", "mfdcountry" : "India", "speed" : 55 }
{ "_id" : ObjectId("5471d72e0ce70a7026ebefee"), "name" : "Esteem", "color" : "JetRed", "cno" : "H414", "mfdcountry" : "Italy", "speed" : 65 }
{ "_id" : 1, "name" : "Polo", "color" : "White", "cno" : "H411", "mfdcountry" : "Germany", "speed" : 45 }
{ "_id" : 2, "name" : "Volkswagen", "color" : "Blue", "cno" : "H412", "mfdcountry" : "Japan", "speed" : 52 }
As you can notice, this sorts the car collection documents in ascending order on the name field.
您会注意到,这会在名称字段上按升序对收车文件进行排序。
>db.car.find().sort({speed:-1,name:1})
{ "_id" : ObjectId("54729a20ab36ed23e31c68f1"), "name" : "Audi", "color" : "Grey", "cno" : "H415", "mfdcountry" : "Rome", "speed" : 65 }
{ "_id" : ObjectId("5471d72e0ce70a7026ebefee"), "name" : "Esteem", "color" : "JetRed", "cno" : "H414", "mfdcountry" : "Italy", "speed" : 65 }
{ "_id" : ObjectId("5472988cab36ed23e31c68f0"), "name" : "skoda", "color" : "JetRed", "cno" : "H415", "mfdcountry" : "Chez", "speed" : 65 }
{ "_id" : 3, "name" : "Alto", "color" : "Silver", "cno" : "H413", "mfdcountry" : "India", "speed" : 55 }
{ "_id" : 2, "name" : "Volkswagen", "color" : "Blue", "cno" : "H412", "mfdcountry" : "Japan", "speed" : 52 }
{ "_id" : 1, "name" : "Polo", "color" : "White", "cno" : "H411", "mfdcountry" : "Germany", "speed" : 45 }
Above example sorts the car collection in descending order based on speed and then sorts on name in ascending order for the cars having same speed (65).
上面的示例基于速度对汽车集合进行降序排序,然后对具有相同速度的汽车按名称进行升序排序(65)。
限制MongoDB排序操作的结果 (Limit the results of MongoDB sort operation)
If the sort operation exceeds more than 32 megabytes, MongoDB returns an error. To get rid of this error, indexing can be used in conjunction with limit method. Limit results the number of documents to be returned within 32 megabytes.
如果排序操作超过32兆字节,则MongoDB返回错误。 为了消除此错误,可以将索引与limit方法结合使用。 限制结果是要返回的32兆字节以内的文档数。
For example;
例如;
>db.car.find().sort( {speed:-1,name:1 }).limit(10)
This MongoDB sort operation limits the number of documents returned to 10 and ensures that it is within 32 megabytes limit.
此MongoDB排序操作将返回的文档数限制为10,并确保该数量在32 MB的范围内。
Indexes can be created as shown below.
可以如下所示创建索引。
>db.car.ensureIndex({ name:1,speed:-1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
This ensures that the index is created for the car collection. We can also use Mongo shell createIndex()
method for this.
这样可以确保为汽车集合创建索引。 我们也可以为此使用Mongo shell createIndex()
方法。
指定投影字段 (Specifying Projection fields)
When user specifies the fields to be projected and sorted the MongoDB engine sorts the resultant documents first.
当用户指定要投影和排序的字段时,MongoDB引擎将首先对生成的文档进行排序。
For example;
例如;
>db.car.find({speed: { $gt:14}},{name:1,speed:1}).sort({"speed":-1})
{ "_id" : 11, "name" : "Polo", "speed" : 45 }
{ "_id" : 10, "name" : "Volkswagen", "speed" : 44 }
{ "_id" : 9, "name" : "Skoda", "speed" : 43 }
{ "_id" : 12, "name" : "Ecosport", "speed" : 15 }
This operation sorts the car by its speed in descending order first and then displays only id, name and speed fields in the resultant document.
此操作首先按降序对汽车进行排序,然后在结果文档中仅显示id,名称和速度字段。
MongoDB排序的自然顺序 (Natural Ordering of MongoDB sort)
The $natural parameter returns all the documents in the order they exist in the database. This ordering basically depicts the order in which the records are inserted except in the conditions where the documents relocate due to update or remove operations.
$ natural参数按它们在数据库中存在的顺序返回所有文档。 该顺序基本上描述了记录的插入顺序,但由于更新或删除操作而导致文档重新定位的情况除外。
For example;
例如;
>db.car.find().sort( { $natural: 1 })
{ "_id" : 9, "name" : "Skoda", "color" : "Red", "cno" : "H622", "mfdcountry" : "Chez", "speed" : 43 }
{ "_id" : 10, "name" : "Volkswagen", "color" : "Blue", "cno" : "H623", "mfdcountry" : "Germany", "speed" : 44 }
{ "_id" : 11, "name" : "Polo", "color" : "White", "cno" : "H624", "mfdcountry" : "Japan", "speed" : 45 }
{ "_id" : 12, "name" : "Ecosport", "color" : "NavyBlue", "cno" : "H625", "mfdcountry" : "Japan", "speed" : 15 }
The documents are retrieved in the order in which they are inserted into the database.
按照将文档插入数据库的顺序来检索文档。
MongoDB排序Java程序 (MongoDB sort Java Program)
In this section we will look into a java program to perform sort operation in ascending and descending orders.
在本节中,我们将研究一个Java程序以升序和降序执行排序操作。
Below is the MongoDB sort program for java driver versions 2.x.
以下是针对Java驱动程序版本2.x的MongoDB排序程序。
package com.journaldev.mongodb;
import java.net.UnknownHostException;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class MongoDBSort {
// method for sorting in ascending order based on name
public static void sortAscending() throws UnknownHostException {
// Get a new connection to the db assuming that it is running
MongoClient m1 = new MongoClient("localhost");
// use test as a datbase,use your database here
DB d1 = m1.getDB("test");
// fetch the collection object ,car is used here,use your own
DBCollection coll = d1.getCollection("car");
// find method is called and result stored in cursor
DBCursor car = coll.find();
// sorting the cursor based in ascending order based on name field
car.sort(new BasicDBObject("name", 1));
// iterating throug cursor and printing all the documents stored in
// cursor
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
// method for sorting in descending order based on speed
public static void sortDescending() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB d1 = m1.getDB("test");
DBCollection coll = d1.getCollection("car");
DBCursor car = coll.find();
// sorting the cursor based in descending order based on speed field
car.sort(new BasicDBObject("speed", -1));
System.out
.println("Sorts in Descending order-------------------------------------------");
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
// method for sorting in descending order based on speed and ascending order
// based on name
public static void sortDescendingAscending() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB d1 = m1.getDB("test");
DBCollection coll = d1.getCollection("car");
DBCursor car = coll.find();
// sort speed in descending order then name in ascending order
car.sort(new BasicDBObject("speed", -1).append("name", 1));
System.out
.println("Combining two fields to sort in ascending and descending orders-----------------");
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
public static void sortlimit() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB d1 = m1.getDB("test");
DBCollection coll = d1.getCollection("car");
DBObject q1 = new BasicDBObject("speed", new BasicDBObject("$gt", 15));
BasicDBObject fields = new BasicDBObject("name", 1).append("speed", 1);
// find method is called and result stored //fetch the collection object
// ,car is used here,use your ownin cursor
DBCursor car = coll.find(q1, fields);
// sorting the cursor based in ascending order based on name field
car.sort(new BasicDBObject("name", -1)).limit(2);
System.out.println("limit--------------------------");
// iterating throug cursor and printing all the documents stored in
// cursor
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
public static void sortProjectionfields() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB db = m1.getDB("test");
DBCollection col = db.getCollection("car");
DBObject query = new BasicDBObject("speed",
new BasicDBObject("$gt", 40));
// fields with name and speed field is specified and only these fields
// are displayed
BasicDBObject fields = new BasicDBObject("name", 1).append("speed", 1);
DBCursor carCursor1 = col.find(query, fields);
System.out
.println("------------------------------------------------------");
try {
while (carCursor1.hasNext()) {
System.out.println(carCursor1.next());
}
} finally {
carCursor1.close();
}
}
public static void sortnaturalordering() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB d1 = m1.getDB("test");
DBCollection coll = d1.getCollection("car");
DBObject q1 = new BasicDBObject("speed", new BasicDBObject("$gt", 15));
BasicDBObject fields = new BasicDBObject("name", 1).append("speed", 1);
// find method is called and result stored
// fetch the collection object ,car is used here,use your own cursor
DBCursor car = coll.find(q1, fields);
// sorting the cursor based in ascending order based on name field
car.sort(new BasicDBObject("$natural", -1));
System.out.println("natural ordering---------------");
// iterating through cursor and printing all the documents stored in
// cursor
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
public static void createIndex(String on, int type)
throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB d1 = m1.getDB("test");
DBCollection coll = d1.getCollection("car");
coll.createIndex(new BasicDBObject(on, type));
System.out.println("created index---------------------");
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}
}
public static void main(String[] args) throws UnknownHostException {
// invoking methods for performing sorting
sortAscending();
sortDescending();
sortDescendingAscending();
sortlimit();
sortProjectionfields();
sortnaturalordering();
createIndex("name", 1);
}
}
Above program results in following output.
上面的程序导致以下输出。
{ "_id" : 3.0 , "name" : "Alto" , "color" : "Silver" , "cno" : "H413" , "mfdcountry" : "India" , "speed" : 55.0}
{ "_id" : { "$oid" : "5471d72e0ce70a7026ebefee"} , "name" : "Esteem" , "color" : "JetRed" , "cno" : "H414" , "mfdcountry" : "Italy" , "speed" : 65.0}
{ "_id" : 1.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "mfdcountry" : "Germany" , "speed" : 45.0}
{ "_id" : 2.0 , "name" : "Volkswagen" , "color" : "Blue" , "cno" : "H412" , "mfdcountry" : "Japan" , "speed" : 52.0}
Sorting in Descending order-------------------------------------------
{ "_id" : { "$oid" : "5471d72e0ce70a7026ebefee"} , "name" : "Esteem" , "color" : "JetRed" , "cno" : "H414" , "mfdcountry" : "Italy" , "speed" : 65.0}
{ "_id" : 3.0 , "name" : "Alto" , "color" : "Silver" , "cno" : "H413" , "mfdcountry" : "India" , "speed" : 55.0}
{ "_id" : 2.0 , "name" : "Volkswagen" , "color" : "Blue" , "cno" : "H412" , "mfdcountry" : "Japan" , "speed" : 52.0}
{ "_id" : 1.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "mfdcountry" : "Germany" , "speed" : 45.0}
sorting ascending descending-----------------
{ "_id" : { "$oid" : "54729a20ab36ed23e31c68f1"} , "name" : "Audi" , "color" : "Grey" , "cno" : "H415" , "mfdcountry" : "Rome" , "speed" : 65.0}
{ "_id" : { "$oid" : "5471d72e0ce70a7026ebefee"} , "name" : "Esteem" , "color" : "JetRed" , "cno" : "H414" , "mfdcountry" : "Italy" , "speed" : 65.0}
{ "_id" : { "$oid" : "5472988cab36ed23e31c68f0"} , "name" : "skoda" , "color" : "JetRed" , "cno" : "H415" , "mfdcountry" : "Chez" , "speed" : 65.0}
{ "_id" : 3.0 , "name" : "Alto" , "color" : "Silver" , "cno" : "H413" , "mfdcountry" : "India" , "speed" : 55.0}
{ "_id" : 2.0 , "name" : "Volkswagen" , "color" : "Blue" , "cno" : "H412" , "mfdcountry" : "Japan" , "speed" : 52.0}
{ "_id" : 1.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "mfdcountry" : "Germany" , "speed" : 45.0}
limit--------------------------
{ "_id" : 10.0 , "name" : "Volkswagen" , "speed" : 44.0}
{ "_id" : 9.0 , "name" : "Skoda" , "speed" : 43.0}
------------------------------------------------------
{ "_id" : 11.0 , "name" : "Polo" , "speed" : 45.0}
{ "_id" : 10.0 , "name" : "Volkswagen" , "speed" : 44.0}
{ "_id" : 9.0 , "name" : "Skoda" , "speed" : 43.0}
natural ordering---------------
{ "_id" : 11.0 , "name" : "Polo" , "speed" : 45.0}
{ "_id" : 10.0 , "name" : "Volkswagen" , "speed" : 44.0}
{ "_id" : 9.0 , "name" : "Skoda" , "speed" : 43.0}
created index---------------------
{ "v" : 1 , "key" : { "_id" : 1} , "name" : "_id_" , "ns" : "test.car"}
{ "v" : 1 , "key" : { "speed" : -1.0 , "name" : 1.0} , "name" : "speed_-1_name_1" , "ns" : "test.car"}
{ "v" : 1 , "key" : { "name" : 1.0 , "speed" : -1.0} , "name" : "name_1_speed_-1" , "ns" : "test.car"}
{ "v" : 1 , "key" : { "name" : 1} , "name" : "name_1" , "ns" : "test.car"}
If you are using MongoDB java driver version 3.x, below code should work. It’s tested with version 3.5.0
如果您使用的是MongoDB Java驱动程序版本3.x,则下面的代码应该可用。 已通过3.5.0版进行测试
package com.journaldev.mongodb.main;
import java.net.UnknownHostException;
import java.util.List;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBSort {
// method for sorting in ascending order based on name
public static void sortAscending() throws UnknownHostException {
// Get a new connection to the db assuming that it is running
MongoClient mc = new MongoClient("localhost");
// use test as a datbase,use your database here
MongoDatabase db = mc.getDatabase("journaldev");
// fetch the collection object ,car is used here,use your own
MongoCollection<Document> coll = db.getCollection("car");
// find method is called and result stored in cursor
FindIterable<Document> car = coll.find();
// sorting the cursor based in ascending order based on name field
car.sort(new BasicDBObject("name", 1));
// iterating through cursor and printing all the documents stored in cursor
MongoCursor<Document> iterator = car.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
// method for sorting in descending order based on speed
public static void sortDescending() throws UnknownHostException {
MongoClient mc = new MongoClient("localhost");
MongoDatabase db = mc.getDatabase("test");
MongoCollection<Document> coll = db.getCollection("car");
FindIterable<Document> car = coll.find();
// sorting the cursor based in descending order based on speed field
car.sort(new BasicDBObject("speed", -1));
System.out.println("Sorts in Descending order");
MongoCursor<Document> iterator = car.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
// method for sorting in descending order based on speed and ascending order
// based on name
public static void sortDescendingAscending() throws UnknownHostException {
MongoClient mc = new MongoClient("localhost");
MongoDatabase db = mc.getDatabase("test");
MongoCollection<Document> coll = db.getCollection("car");
FindIterable<Document> car = coll.find();
// sort speed in descending order then name in ascending order
car.sort(new BasicDBObject("speed", -1).append("name", 1));
System.out.println("Combining two fields to sort in ascending and descending orders");
MongoCursor<Document> iterator = car.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
public static void sortlimit() throws UnknownHostException {
MongoClient mc = new MongoClient("localhost");
MongoDatabase db = mc.getDatabase("test");
MongoCollection<Document> coll = db.getCollection("car");
BasicDBObject q1 = new BasicDBObject("speed", new BasicDBObject("$gt", 15));
// find method is called and result stored //fetch the collection object
// ,car is used here,use your ownin cursor
FindIterable<Document> car = coll.find(q1);
// sorting the cursor based in ascending order based on name field
car.sort(new BasicDBObject("name", -1)).limit(2);
System.out.println("limit example");
// iterating through cursor and printing all the documents stored in
// cursor
MongoCursor<Document> iterator = car.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
public static void sortProjectionfields() throws UnknownHostException {
MongoClient mc = new MongoClient("localhost");
MongoDatabase db = mc.getDatabase("test");
MongoCollection<Document> col = db.getCollection("car");
BasicDBObject query = new BasicDBObject("speed",
new BasicDBObject("$gt", 40));
FindIterable<Document> carCursor1 = col.find(query);
System.out.println("------------------------------------------------------");
MongoCursor<Document> iterator = carCursor1.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
public static void sortnaturalordering() throws UnknownHostException {
MongoClient mc = new MongoClient("localhost");
MongoDatabase db = mc.getDatabase("test");
MongoCollection<Document> coll = db.getCollection("car");
BasicDBObject q1 = new BasicDBObject("speed", new BasicDBObject("$gt", 15));
BasicDBObject fields = new BasicDBObject("name", 1).append("speed", 1);
// find method is called and result stored
// fetch the collection object ,car is used here,use your own cursor
FindIterable<Document> car = coll.find(q1);
// sorting the cursor based in ascending order based on name field
car.sort(new BasicDBObject("$natural", -1));
System.out.println("natural ordering---------------");
// iterating through cursor and printing all the documents stored in
// cursor
MongoCursor<Document> iterator = car.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
public static void createIndex(String on, int type)
throws UnknownHostException {
MongoClient mc = new MongoClient("localhost");
MongoDatabase db = mc.getDatabase("test");
MongoCollection<Document> coll = db.getCollection("car");
String indexName = coll.createIndex(new BasicDBObject(on, type));
System.out.println("created index name="+indexName);
MongoCursor<Document> iterator = coll.listIndexes().iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} finally {
iterator.close();
mc.close();
}
}
public static void main(String[] args) throws UnknownHostException {
// invoking methods for performing sorting
sortAscending();
sortDescending();
sortDescendingAscending();
sortlimit();
sortProjectionfields();
sortnaturalordering();
createIndex("name", 1);
}
}
That’s all for sorting documents in MongoDB, we will look into more of MongoDB features in coming posts.
这就是在MongoDB中对文档进行排序的全部内容,我们将在以后的文章中探讨MongoDB的更多功能。
mongodb排序