MongoDB将带有数组的记录转换为新集合中的多个记录
为此,可以将$out与aggregate()和$undend一起使用。让我们用文档创建一个集合
> db.demo757.insertOne( ... { ... "id": 101, ... "Name": ["John", "Bob", "Chris"] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb025745637cd592b2a4ae2") } > db.demo757.insertOne( ... { ... "id": 102, ... "Name": ["David"] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb025755637cd592b2a4ae3") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo757.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb025745637cd592b2a4ae2"), "id" : 101, "Name" : [ "John", "Bob", "Chris" ] } { "_id" : ObjectId("5eb025755637cd592b2a4ae3"), "id" : 102, "Name" : [ "David" ] }
以下是将具有数组的一个记录转换为新集合中的多个记录的查询-
> db.demo757.aggregate([ ... {$unwind: '$Name'}, ... {$project: {_id: 0}}, ... {$out: 'demo758'} ... ]) > db.demo758.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb02582192bedc4738b5881"), "id" : 101, "Name" : "John" } { "_id" : ObjectId("5eb02582192bedc4738b5882"), "id" : 101, "Name" : "Bob" } { "_id" : ObjectId("5eb02582192bedc4738b5883"), "id" : 101, "Name" : "Chris" } { "_id" : ObjectId("5eb02582192bedc4738b5884"), "id" : 102, "Name" : "David" }