![](/img/trans.png)
[英]Create index on a converted sub document field with Spring Data MongoDB
[英]How to create an index on the “name” field of a document in mongodb
我想在mongodb中的文檔的名稱字段上創建索引,以便在執行查找時,我應該將所有名稱按字母順序顯示。如何實現此目的? 誰能幫我...
我在mongodb中的文檔:
db.col.find();
{ "_id" : ObjectId("5696256b0c50bf42dcdfeae1"), "name" : "Daniel", "age" : 24 }
{ "_id" : ObjectId("569625850c50bf42dcdfeae2"), "name" : "Asha", "age" : 21 }
{ "_id" : ObjectId("569625a40c50bf42dcdfeae3"), "name" : "Hampi", "age" : 34 }
{ "_id" : ObjectId("5696260f0c50bf42dcdfeae5"), "name" : "Bhavana", "age" : 14 }
實際上,您不需要索引即可按字母順序顯示結果。 您需要的是.sort()
方法。
db.collection.find().sort({'name': 1})
哪個返回
{ "_id" : ObjectId("569625850c50bf42dcdfeae2"), "name" : "Asha", "age" : 21 }
{ "_id" : ObjectId("5696260f0c50bf42dcdfeae5"), "name" : "Bhavana", "age" : 14 }
{ "_id" : ObjectId("5696256b0c50bf42dcdfeae1"), "name" : "Daniel", "age" : 24 }
{ "_id" : ObjectId("569625a40c50bf42dcdfeae3"), "name" : "Hampi", "age" : 34 }
在文檔中的字段上創建索引不會自動對您仍然需要使用.sort()
方法的特定字段上的結果進行排序。 請參閱使用索引對查詢結果進行排序
如果.aggregate()
升序返回文檔中所有名稱的數組,則需要使用.aggregate()
方法。
管道的第一個階段是$sort
階段,您可以按“名稱”的升序對文檔進行排序。 最后一個階段是$group
階段,在此階段您將文檔分組並使用$push
累加器運算符返回“名稱”數組
db.collection.aggregate([
{ "$sort": { "name": 1 } },
{ "$group": { "_id": null, "names": { "$push": "$name" } } }
])
產生:
{ "_id" : null, "names" : [ "Asha", "Bhavana", "Daniel", "Hampi" ] }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.