以下是在MongoDB中使用排序数据获取不同值的查询
db.yourCollectionName.distinct("yourFieldName").sort();
首先让我们创建一个包含文档的集合
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e3315e86fd1496b38c3") } >db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e3e15e86fd1496b38c4") } >db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e4415e86fd1496b38c5") } >db.getDistinctWithSortedDataDemo.insertOne({"StudentId":30,"StudentName":"Chris","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e5115e86fd1496b38c6") } >db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e5715e86fd1496b38c7") } >db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e6515e86fd1496b38c8") } >db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","Stude ntAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1e6d15e86fd1496b38c9") }
以下是在find()
方法的帮助下显示集合中所有文档的查询;
> db.getDistinctWithSortedDataDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9b1e3315e86fd1496b38c3"), "StudentId" : 10, "StudentName" : "John", "StudentAge" : 23 } { "_id" : ObjectId("5c9b1e3e15e86fd1496b38c4"), "StudentId" : 20, "StudentName" : "Carol", "StudentAge" : 21 } { "_id" : ObjectId("5c9b1e4415e86fd1496b38c5"), "StudentId" : 10, "StudentName" : "John", "StudentAge" : 23 } { "_id" : ObjectId("5c9b1e5115e86fd1496b38c6"), "StudentId" : 30, "StudentName" : "Chris", "StudentAge" : 22 } { "_id" : ObjectId("5c9b1e5715e86fd1496b38c7"), "StudentId" : 20, "StudentName" : "Carol", "StudentAge" : 21 } { "_id" : ObjectId("5c9b1e6515e86fd1496b38c8"), "StudentId" : 40, "StudentName" : "Bob", "StudentAge" : 20 } { "_id" : ObjectId("5c9b1e6d15e86fd1496b38c9"), "StudentId" : 40, "StudentName" : "Bob", "StudentAge" : 20 }
以下是查询以获取带有“ StudentName”排序数据的不同值的查询
> db.getDistinctWithSortedDataDemo.distinct("StudentName").sort();
这将产生以下输出
[ "Bob", "Carol", "Chris", "John" ]
以下是查询以获取带有StudentAge排序数据的不同值
> db.getDistinctWithSortedDataDemo.distinct("StudentAge").sort();
这将产生以下输出
[ 20, 21, 22, 23 ]