在MongoDB中算出不同的价值吗?
使用长度的概念来计算不同的值。以下是语法-
db.yourCollectionName.distinct("yourFieldName").length;让我们创建一个包含文档的集合-
> db.countDistinctDemo.insertOne({"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6166de8cc557214c0dfa")
}
> db.countDistinctDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd616ade8cc557214c0dfb")
}
> db.countDistinctDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd616cde8cc557214c0dfc")
}
> db.countDistinctDemo.insertOne({"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6170de8cc557214c0dfd")
}
> db.countDistinctDemo.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6175de8cc557214c0dfe")
}
> db.countDistinctDemo.insertOne({"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6181de8cc557214c0dff")
}在find()方法的帮助下显示集合中的所有文档-
> db.countDistinctDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cbd6166de8cc557214c0dfa"), "StudentName" : "John" }
{ "_id" : ObjectId("5cbd616ade8cc557214c0dfb"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cbd616cde8cc557214c0dfc"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cbd6170de8cc557214c0dfd"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5cbd6175de8cc557214c0dfe"), "StudentName" : "David" }
{ "_id" : ObjectId("5cbd6181de8cc557214c0dff"), "StudentName" : "Carol" }以下是计算非重复值的查询-
> db.countDistinctDemo.distinct("StudentName").length;这将产生以下输出-
4
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短