MongoDB 是否可以将带有数组的单条记录转换为新集合中的多条记录?
为此,你可以使用 $out 和 aggregate() 和 $unwind。让我们创建一个带有文件的集合 −
> 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" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP