为了更快地查询,请创建一个索引。要获取计数,请使用count()
。让我们创建一个包含文档的集合-
> db.demo311.ensureIndex({"Name":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo311.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd01f8647eb59e562044") } > db.demo311.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd05f8647eb59e562045") } > db.demo311.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd06f8647eb59e562046") } > db.demo311.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd0af8647eb59e562047") } > db.demo311.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd0df8647eb59e562048") } > db.demo311.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd0ff8647eb59e562049") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo311.find();
这将产生以下输出-
{ "_id" : ObjectId("5e50cd01f8647eb59e562044"), "Name" : "Chris" } { "_id" : ObjectId("5e50cd05f8647eb59e562045"), "Name" : "David" } { "_id" : ObjectId("5e50cd06f8647eb59e562046"), "Name" : "David" } { "_id" : ObjectId("5e50cd0af8647eb59e562047"), "Name" : "Chris" } { "_id" : ObjectId("5e50cd0df8647eb59e562048"), "Name" : "Bob" } { "_id" : ObjectId("5e50cd0ff8647eb59e562049"), "Name" : "Chris" }
以下是获取特定值的计数的查询-
> db.demo311.find({"Name":"Chris"}).count();
这将产生以下输出-
3