将 MongoDB 聚合成一个单独的文档,其中带有一个数组?
对于 MongoDB 中的聚合,请使用 aggregate()。让我们创建一个包含文档的集合 −
> db.demo248.insertOne({"id":101,"Name":"Chris","Age":21,"CountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b6651627c0c63e7dba6d") } > db.demo248.insertOne({"id":101,"Name":"Bob","Age":22,"CountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b6741627c0c63e7dba6e") } > db.demo248.insertOne({"id":102,"Name":"Mike","Age":20,"CountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b6811627c0c63e7dba6f") }
在 find() 方法的帮助下,显示集合中的所有文档 −
> db.demo248.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e46b6651627c0c63e7dba6d"), "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" } { "_id" : ObjectId("5e46b6741627c0c63e7dba6e"), "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" } { "_id" : ObjectId("5e46b6811627c0c63e7dba6f"), "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" }
以下是将多个文档转换为具有数组的单个文档的查询 −
> db.demo248.aggregate([ ... { ... $group : { ... _id : "$id", ... details : { ... $push : { ... id:"$id", ... Name:"$Name", ... Age:"$Age", ... CountryName:"$CountryName" ... } ... } ... } ... } ...])
这将产生以下输出 −
{ "_id" : 102, "details" : [ { "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" } ] } { "_id" : 101, "details" : [ { "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" } ] }
广告