在MongoDB中找到字段的所有非唯一值?
使用aggregate()
方法获取字段的所有非唯一值。首先让我们创建一个包含文档的集合
> db.findAllNonDistinctDemo.insertOne({"UserName":"John","UserAge":28});{
"acknowledged" : true,
"insertedId" : ObjectId("5c995078863d6ffd454bb647")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Larry","UserAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c995081863d6ffd454bb648")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Larry","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c995089863d6ffd454bb649")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"David","UserAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c995093863d6ffd454bb64a")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"John","UserAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c99509d863d6ffd454bb64b")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Robert","UserAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9950a7863d6ffd454bb64c")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Robert","UserAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9950b1863d6ffd454bb64d")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Mike","UserAge":29});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9950bc863d6ffd454bb64e")
}
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.findAllNonDistinctDemo.find().pretty();
这将产生以下输出
{"_id" : ObjectId("5c995078863d6ffd454bb647"),
"UserName" : "John",
"UserAge" : 28
}
{
"_id" : ObjectId("5c995081863d6ffd454bb648"),
"UserName" : "Larry",
"UserAge" : 21
}
{
"_id" : ObjectId("5c995089863d6ffd454bb649"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c995093863d6ffd454bb64a"),
"UserName" : "David",
"UserAge" : 22
}
{
"_id" : ObjectId("5c99509d863d6ffd454bb64b"),
"UserName" : "John",
"UserAge" : 26
}
{
"_id" : ObjectId("5c9950a7863d6ffd454bb64c"),
"UserName" : "Robert",
"UserAge" : 24
}
{
"_id" : ObjectId("5c9950b1863d6ffd454bb64d"),
"UserName" : "Robert",
"UserAge" : 25
}
{
"_id" : ObjectId("5c9950bc863d6ffd454bb64e"),
"UserName" : "Mike",
"UserAge" : 29
}
以下是查找MongoDB中字段的所有非唯一值的查询
> db.findAllNonDistinctDemo.aggregate([... { "$group": {
... "_id": "$UserName",
... "Counter": { "$sum": 1 }
... }},
... { "$match": {
... "Counter": { "$gt": 1 }
... }}
... ]).pretty();
这将产生以下输出
{ "_id" : "Robert", "Counter" : 2 }{ "_id" : "Larry", "Counter" : 2 }
{ "_id" : "John", "Counter" : 2 }
以上是 在MongoDB中找到字段的所有非唯一值? 的全部内容, 来源链接: utcz.com/z/340971.html