MongoDB 'count()' 非常慢。我们如何解决它?
您可以ensureIndex()用来提高count()MongoDB中方法的性能。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.countPerformanceDemo.insertOne({"StudentName":"John","StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebcf82f684a30fbdfd55f")
}
> db.countPerformanceDemo.insertOne({"StudentName":"Mike","StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebd042f684a30fbdfd560")
}
> db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebd112f684a30fbdfd561")
}
> db.countPerformanceDemo.insertOne({"StudentName":"Carol","StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebd1a2f684a30fbdfd562")
}
> db.countPerformanceDemo.insertOne({"StudentName":"Bob","StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebd212f684a30fbdfd563")
}
> db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebd9a2f684a30fbdfd564")
}
> db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ebd9e2f684a30fbdfd565")
}在find()方法的帮助下显示集合中的所有文档。查询如下-
> db.countPerformanceDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c8ebcf82f684a30fbdfd55f"),
"StudentName" : "John",
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c8ebd042f684a30fbdfd560"),
"StudentName" : "Mike",
"StudentCountryName" : "UK"
}
{
"_id" : ObjectId("5c8ebd112f684a30fbdfd561"),
"StudentName" : "David",
"StudentCountryName" : "AUS"
}
{
"_id" : ObjectId("5c8ebd1a2f684a30fbdfd562"),
"StudentName" : "Carol",
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c8ebd212f684a30fbdfd563"),
"StudentName" : "Bob",
"StudentCountryName" : "UK"
}
{
"_id" : ObjectId("5c8ebd9a2f684a30fbdfd564"),
"StudentName" : "David",
"StudentCountryName" : "UK"
}
{
"_id" : ObjectId("5c8ebd9e2f684a30fbdfd565"),
"StudentName" : "David",
"StudentCountryName" : "US"
}这是获取高性能形式的查询count()-
> db.countPerformanceDemo.ensureIndex({"StudentName":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}现在,实现count()方法。它计算StudentName为“David”的记录:
> db.countPerformanceDemo.find({"StudentName":"David"}).count();以下是输出-
3
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下