获取MongoDB查询中所有文档的大小?
要获取查询中所有文档的大小,您需要遍历文档。首先让我们创建一个包含文档的集合-
> db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"John","StudentSubject":["MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c0c1edc6604c74817cd7") } > db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"Larry","StudentSubject":["MySQL","PHP"],"StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c0d9edc6604c74817cd8") } > db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"Chris","StudentSubject":["SQL Server","C#"],"StudentAge":23,"StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c0fbedc6604c74817cd9") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.sizeOfAllDocumentsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd3c0c1edc6604c74817cd7"), "StudentFirstName" : "John", "StudentSubject" : [ "MongoDB", "Java" ] } { "_id" : ObjectId("5cd3c0d9edc6604c74817cd8"), "StudentFirstName" : "Larry", "StudentSubject" : [ "MySQL", "PHP" ], "StudentAge" : 21 } { "_id" : ObjectId("5cd3c0fbedc6604c74817cd9"), "StudentFirstName" : "Chris", "StudentSubject" : [ "SQL Server", "C#" ], "StudentAge" : 23, "StudentCountryName" : "US" }
以下是查询以获取查询中所有文档的大小-
> var allDocument = db.sizeOfAllDocumentsDemo.find(); > var counter = 0; > allDocument.forEach( ... function(myDocument) { ... counter = counter+Object.bsonsize(myDocument) ... } ... ); > print(counter);
这将产生以下输出-
358