MongoDB 查询如何才能统计数组的大小?
使用 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
广告