MongoDB查询以计数由另一个字段分组的唯一字段的数量?
为此,请使用aggregate()并与$group一起使用。让我们创建一个包含文档的集合-
> db.demo354.insertOne({"Name1":"Chris","Name2":"David"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e5685a6f8647eb59e5620c0")
}
> db.demo354.insertOne({"Name1":"Chris","Name2":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5685a9f8647eb59e5620c1")
}
> db.demo354.insertOne({"Name1":"Chris","Name2":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5685aff8647eb59e5620c2")
}
> db.demo354.insertOne({"Name1":"Carol","Name2":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5685c4f8647eb59e5620c3")
}
> db.demo354.insertOne({"Name1":"Carol","Name2":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5685c5f8647eb59e5620c4")
}
在find()方法的帮助下显示集合中的所有文档-
> db.demo354.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5685a6f8647eb59e5620c0"), "Name1" : "Chris", "Name2" : "David" }{ "_id" : ObjectId("5e5685a9f8647eb59e5620c1"), "Name1" : "Chris", "Name2" : "David" }
{ "_id" : ObjectId("5e5685aff8647eb59e5620c2"), "Name1" : "Chris", "Name2" : "Bob" }
{ "_id" : ObjectId("5e5685c4f8647eb59e5620c3"), "Name1" : "Carol", "Name2" : "John" }
{ "_id" : ObjectId("5e5685c5f8647eb59e5620c4"), "Name1" : "Carol", "Name2" : "John" }
以下是用于计算由另一个字段分组的唯一字段的数量的查询-
> db.demo354.aggregate([... {
... $group: {
... _id: {
... "Name1": "$Name1",
... "Name2": "$Name2"
... },
... }
... },
... {
... $group: {
... _id: "$_id.Name1",
... "Name2": { $sum: 1 }
... }
... },
... {
... $project: {
... _id: 0,
... Name1: "$_id",
... Name2: 1
... }
... }
... ])
这将产生以下输出-
{ "Name2" : 2, "Name1" : "Chris" }{ "Name2" : 1, "Name1" : "Carol" }
以上是 MongoDB查询以计数由另一个字段分组的唯一字段的数量? 的全部内容, 来源链接: utcz.com/z/322507.html