对于此类匹配和计数,请在MongoDB中使用$match。让我们创建一个包含文档的集合-
> db.demo726.insertOne(
... {
... id:101,
... "details": [
... {
... Name:"Chris"
...
... },
... {
... Name:"Chris"
...
... },
... {
... Name:"Bob"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab318643417811278f5894")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo726.find();
这将产生以下输出-
{ "_id" : ObjectId("5eab318643417811278f5894"), "id" : 101, "details" : [ { "Name" : "Chris" }, { "Name" : "Chris" }, { "Name" : "Bob" } ] }以下是基于MongoDB中特定字段的值对数组中的文档进行计数的查询-
> db.demo726.aggregate([
...
... { $unwind: '$details' },
...
... { $match: { 'details.Name': "Chris"} },
... { $group: {
... _id: "$Name",
... Total_Value: { $sum: 1 }
... }
... }
... ]);这将产生以下输出-
{ "_id" : null, "Total_Value" : 2 }