使用 MongoDB $group 获取值列表?
要获取值列表,可使用 $group 聚合和 $push 运算符。我们首先创建一个带有文档的集合 -
> db.groupByDemo.insertOne({"UserName":"John","Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69f0457806ebf1256f136") } > db.groupByDemo.insertOne({"UserName":"Larry","Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69f0657806ebf1256f137") } > db.groupByDemo.insertOne({"UserName":"John","Subject":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69f0d57806ebf1256f138") } > db.groupByDemo.insertOne({"UserName":"John","Subject":"C"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69f1357806ebf1256f139") } > db.groupByDemo.insertOne({"UserName":"Larry","Subject":"SQL Server"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69f1c57806ebf1256f13a") }
以下是使用 find() 方法显示来自集合的所有文档的查询 -
> db.groupByDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cd69f0457806ebf1256f136"), "UserName" : "John", "Subject" : "MongoDB" } { "_id" : ObjectId("5cd69f0657806ebf1256f137"), "UserName" : "Larry", "Subject" : "MySQL" } { "_id" : ObjectId("5cd69f0d57806ebf1256f138"), "UserName" : "John", "Subject" : "Java" } { "_id" : ObjectId("5cd69f1357806ebf1256f139"), "UserName" : "John", "Subject" : "C" } { "_id" : ObjectId("5cd69f1c57806ebf1256f13a"), "UserName" : "Larry", "Subject" : "SQL Server" }
以下是使用 $group 和 $push 获取值列表的查询 -
> db.groupByDemo.aggregate({$group: { '_id': '$UserName', 'Subject': { $push: '$Subject'}}});
这将产生以下输出 -
{ "_id" : "Larry", "Subject" : [ "MySQL", "SQL Server" ] } { "_id" : "John", "Subject" : [ "MongoDB", "Java", "C" ] }
广告