在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 简短大气的狗年祝福语