MongoDB排序

时间:2020-02-23 14:40:52  来源:igfitidea点击:

MongoDB排序方法按用户在输入参数中指定的升序或者降序对文档进行排序。

MongoDB排序

MongoDB排序方法的语法为:

{ $sort:{<field1>:<sort order>........}}

排序顺序可以采用以下值:

1:指定字段应按升序排序

-1:指定字段应按降序排序

MongoDB排序示例

让我们看一个对字段排序的例子。
请注意,您可以使用MongoDB插入来创建示例数据。

>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" : "San Franceco", "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 }

按速度字段的降序对收车文档进行排序。

>db.car.find().sort({name:1})

{ "_id" : 3, "name" : "Alto", "color" : "Silver", "cno" : "H413", "mfdcountry" : "San Franceco", "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 }

您会注意到,这会在名称字段上按升序对收车文件进行排序。

>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" : "San Franceco", "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 }

上面的示例基于速度对汽车集合进行降序排序,然后对具有相同速度的汽车按名称进行升序排序(65)。

限制MongoDB排序操作的结果

如果排序操作超过32兆字节,则MongoDB返回错误。
为了消除此错误,可以将索引与limit方法结合使用。
限制结果是要返回的32兆字节以内的文档数。

例如;

>db.car.find().sort( {speed:-1,name:1 }).limit(10)

此MongoDB排序操作将返回的文档数限制为10,并确保该数量在32 MB的范围内。

可以如下所示创建索引。

>db.car.ensureIndex({ name:1,speed:-1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 2,
	"numIndexesAfter" : 3,
	"ok" : 1
}

这样可以确保为汽车集合创建索引。
我们也可以使用Mongo shell的createIndex()方法。

指定投影字段

当用户指定要投影和排序的字段时,MongoDB引擎将首先对生成的文档进行排序。

例如;

>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 }

此操作首先按速度降序对汽车进行排序,然后在结果文档中仅显示id,名称和速度字段。

MongoDB排序的自然顺序

$natural参数按数据库中存在的顺序返回所有文档。
该顺序基本上描述了记录的插入顺序,但由于更新或者删除操作而导致文档重新定位的情况除外。

例如;

>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 }

按照将文档插入数据库的顺序来检索文档。

MongoDB排序Java程序

在本节中,我们将研究一个Java程序以升序和降序执行排序操作。

以下是针对Java驱动程序版本2.x的MongoDB排序程序。

package com.theitroad.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);
	}

}

上面的程序导致以下输出。

{ "_id" : 3.0 , "name" : "Alto" , "color" : "Silver" , "cno" : "H413" , "mfdcountry" : "San Franceco" , "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" : "San Franceco" , "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" : "San Franceco" , "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"}

如果您使用的是MongoDB Java驱动程序版本3.x,则以下代码应可用。
已通过3.5.0版进行测试

package com.theitroad.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("theitroad");

		//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);
	}

}