为什么 MongoDB 查找记录需要花费太多时间?
在这种情况下,使用特定字段的索引概念。让我们先使用文档创建一个集合。在这里,我们还使用 createIndex() 创建了索引 −
> db.decreasetimeusingindex.createIndex({"StudentName":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.decreasetimeusingindex.insertOne({"StudentName":"John Smith","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e03960af5e889d7a51994ff")
}
> db.decreasetimeusingindex.insertOne({"StudentName":"John Doe","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e039611f5e889d7a5199500")
}
> db.decreasetimeusingindex.insertOne({"StudentName":"Adam Smith","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e03961df5e889d7a5199501")
}以下是使用 find() 方法从集合中显示所有文档的查询 −
> db.decreasetimeusingindex.find().pretty();
这将生成以下输出 −
{
"_id" : ObjectId("5e03960af5e889d7a51994ff"),
"StudentName" : "John Smith",
"StudentAge" : 21
}
{
"_id" : ObjectId("5e039611f5e889d7a5199500"),
"StudentName" : "John Doe",
"StudentAge" : 24
}
{
"_id" : ObjectId("5e03961df5e889d7a5199501"),
"StudentName" : "Adam Smith",
"StudentAge" : 22
}以下是查找特定记录的查询 −
> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"});这将生成以下输出 −
{ "_id" : ObjectId("5e03961df5e889d7a5199501"), "StudentName" : "Adam Smith", "StudentAge" : 22 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP