使用 MongoDB 获取数组中不同值的长度

mongodbdatabasebig data analytics更新于 2026/1/9 2:37:17

要获取不同值,请使用 MongoDB DISTINCT。要获取长度,请使用 LENGTH()。让我们创建一个包含文档的集合 −

> db.demo36.insertOne({"Names":["Chris","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17643bcfb11e5c34d898d4")
}
> db.demo36.insertOne({"Names":["Mike","Sam","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176449cfb11e5c34d898d5")
}
> db.demo36.insertOne({"Names":["Chris","Bob","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17645bcfb11e5c34d898d6")
}

借助 find() 方法显示集合中的所有文档 −

> db.demo36.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e17643bcfb11e5c34d898d4"), "Names" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e176449cfb11e5c34d898d5"), "Names" : [ "Mike", "Sam", "Carol" ] }
{ "_id" : ObjectId("5e17645bcfb11e5c34d898d6"), "Names" : [ "Chris", "Bob", "David" ] }

以下是获取长度的查询 −

> db.demo36.distinct('Names').length;

这将产生以下输出 −

6

相关文章