要订购列表,请使用sort()
。让我们创建一个包含文档的集合-
> db.demo581.insertOne({"Name":"Chris","Score":56});{ "acknowledged" : true, "insertedId" : ObjectId("5e91cbbbfd2d90c177b5bcb6") } > db.demo581.insertOne({"Name":"Bob","Score":240});{ "acknowledged" : true, "insertedId" : ObjectId("5e91cbbbfd2d90c177b5bcb7") } > db.demo581.insertOne({"Name":"David","Score":150});{ "acknowledged" : true, "insertedId" : ObjectId("5e91cbbcfd2d90c177b5bcb8") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo581.find();
这将产生以下输出-
{ "_id" : ObjectId("5e91cbbbfd2d90c177b5bcb6"), "Name" : "Chris", "Score" : 56 } { "_id" : ObjectId("5e91cbbbfd2d90c177b5bcb7"), "Name" : "Bob", "Score" : 240 } { "_id" : ObjectId("5e91cbbcfd2d90c177b5bcb8"), "Name" : "David", "Score" : 150 }
以下是查询列表顺序并将其位置添加到MongoDB中的项目的查询-
> db.demo581.createIndex({Score:1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > var i = 1; > db.demo581.find().sort({"Score": 1}).forEach(function (d){ ... d.Position = i; ... i++; ... db.demo581.save(d); ... })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo581.find();
这将产生以下输出-
{ "_id" : ObjectId("5e91cbbbfd2d90c177b5bcb6"), "Name" : "Chris", "Score" : 56, "Position" : 1 } { "_id" : ObjectId("5e91cbbbfd2d90c177b5bcb7"), "Name" : "Bob", "Score" : 240, "Position" : 3 } { "_id" : ObjectId("5e91cbbcfd2d90c177b5bcb8"), "Name" : "David", "Score" : 150, "Position" : 2 }