首先让我们创建一个包含文档的集合-
> db.demo232.insertOne({_id:101,Name:"Chris"}); { "acknowledged" : true, "insertedId" : 101 } > db.demo232.insertOne({_id:102,Name:"Bob"}); { "acknowledged" : true, "insertedId" : 102 } > db.demo232.insertOne({_id:103,Name:"Bob"}); { "acknowledged" : true, "insertedId" : 103 } > db.demo232.insertOne({_id:104,Name:"David"}); { "acknowledged" : true, "insertedId" : 104 } > db.demo232.insertOne({_id:105,Name:"Chris"}); { "acknowledged" : true, "insertedId" : 105 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo232.find();
这将产生以下输出-
{ "_id" : 101, "Name" : "Chris" } { "_id" : 102, "Name" : "Bob" } { "_id" : 103, "Name" : "Bob" } { "_id" : 104, "Name" : "David" } { "_id" : 105, "Name" : "Chris" }
以下是查询以获取MongoDB中名称记录的频率-
> db.demo232.aggregate( { $group : {_id : "$Name", Frequency : { $sum : 1 }} } );
这将产生以下输出-
{ "_id" : "David", "Frequency" : 1 } { "_id" : "Bob", "Frequency" : 2 } { "_id" : "Chris", "Frequency" : 2 }