为了改善MongoDB中的查询字段,您需要使用索引。让我们创建包含文档的集合
> db.improveQueryDemo.insertOne( ... { ... "PlayerDetails":[ ... {"PlayerName": "John", "PlayerGameScore": 5690}, ... {"PlayerName": "Carol", "PlayerGameScore": 2690}, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c9dbaf875e2eeda1d5c3670") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.improveQueryDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9dbaf875e2eeda1d5c3670"), "PlayerDetails" : [ { "PlayerName" : "John", "PlayerGameScore" : 5690 }, { "PlayerName" : "Carol", "PlayerGameScore" : 2690 } ] }
现在,您需要在字段上创建索引以改善查询。以下是查询
> db.improveQueryDemo.ensureIndex({"PlayerDetails.PlayerName":1});
这将产生以下输出
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
现在,您可以按完全匹配进行搜索。以下是查询
> db.improveQueryDemo.find({"PlayerDetails.PlayerName":"Carol"}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9dbaf875e2eeda1d5c3670"), "PlayerDetails" : [ { "PlayerName" : "John", "PlayerGameScore" : 5690 }, { "PlayerName" : "Carol", "PlayerGameScore" : 2690 } ] }