首先让我们创建一个包含文档的集合-
> dbmongoDBCollectionSizeDemoinsertOne({"Name":"John", "Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23e3db64a577be5a2bc16") } > dbmongoDBCollectionSizeDemoinsertOne({"Name":"Chris", "Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23e45b64a577be5a2bc17") } > dbmongoDBCollectionSizeDemoinsertOne({"Name":"Robert", "Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23e4db64a577be5a2bc18") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> dbmongoDBCollectionSizeDemofind();
这将产生以下文件-
{ "_id" : ObjectId("5cf23e3db64a577be5a2bc16"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5cf23e45b64a577be5a2bc17"), "Name" : "Chris", "Age" : 24 } { "_id" : ObjectId("5cf23e4db64a577be5a2bc18"), "Name" : "Robert", "Age" : 26 }
以下是使用条件获取集合大小的查询-
> var collectionsize = 0; > dbmongoDBCollectionSizeDemofind({Name:'Robert'})forEach(function(d) { var s = Objectbsonsize(d); collectionsize=collectionsize +s; }) > print(collectionsize);
这将产生以下文件-
52