要匹配特定的字段值,请在MongoDB聚合中使用$match。让我们创建一个包含文档的集合-
> db.demo555.insertOne({"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f21bf54b4472ed3e8e85f") } > db.demo555.insertOne({"CountryName":"UK"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f21c254b4472ed3e8e860") } > db.demo555.insertOne({"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f21c354b4472ed3e8e861") } > db.demo555.insertOne({"CountryName":"AUS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f21c554b4472ed3e8e862") } > db.demo555.insertOne({"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f21c754b4472ed3e8e863") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo555.find();
这将产生以下输出:-
{ "_id" : ObjectId("5e8f21bf54b4472ed3e8e85f"), "CountryName" : "US" } { "_id" : ObjectId("5e8f21c254b4472ed3e8e860"), "CountryName" : "UK" } { "_id" : ObjectId("5e8f21c354b4472ed3e8e861"), "CountryName" : "US" } { "_id" : ObjectId("5e8f21c554b4472ed3e8e862"), "CountryName" : "AUS" } { "_id" : ObjectId("5e8f21c754b4472ed3e8e863"), "CountryName" : "US" }
以下是匹配特定字段值的查询-
> db.demo555.aggregate([ ... {$match: {CountryName: 'US'}}, ... {$group: {_id: null, Total: {$sum: 1}}} ... ])
这将产生以下输出-
{ "_id" : null, "Total" : 3 }