使用DISTINCT表示不同的元素,然后使用length获得数组的大小-
db.yourCollectionName.distinct('yourFieldName').length;
首先让我们创建一个包含文档的集合-
> db.countOrSizeDemo.insertOne({"StudentFirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd304f5b64f4b851c3a13dc") } > db.countOrSizeDemo.insertOne({"StudentFirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd304fab64f4b851c3a13dd") } > db.countOrSizeDemo.insertOne({"StudentFirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd304fcb64f4b851c3a13de") } > db.countOrSizeDemo.insertOne({"StudentFirstName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd30500b64f4b851c3a13df") } > db.countOrSizeDemo.insertOne({"StudentFirstName":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd30505b64f4b851c3a13e0") } > db.countOrSizeDemo.insertOne({"StudentFirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3050ab64f4b851c3a13e1") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.countOrSizeDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5cd304f5b64f4b851c3a13dc"), "StudentFirstName" : "John" } { "_id" : ObjectId("5cd304fab64f4b851c3a13dd"), "StudentFirstName" : "David" } { "_id" : ObjectId("5cd304fcb64f4b851c3a13de"), "StudentFirstName" : "David" } { "_id" : ObjectId("5cd30500b64f4b851c3a13df"), "StudentFirstName" : "Carol" } { "_id" : ObjectId("5cd30505b64f4b851c3a13e0"), "StudentFirstName" : "Sam" } { "_id" : ObjectId("5cd3050ab64f4b851c3a13e1"), "StudentFirstName" : "John" }
以下是获取查询数组大小的查询-
> db.countOrSizeDemo.distinct('StudentFirstName').length;
这将产生以下输出-
4