在MongoDB中制作多个数组的数组?
要使多个数组组成一个数组,请在MongoDB聚合中使用$unwind。让我们创建一个包含文档的集合-
> db.demo289.insertOne({"Section":["A","B","E"],"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4c06fcf49383b52759cbc3") } > db.demo289.insertOne({"Section":["C","D","B"],"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4c070af49383b52759cbc4") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo289.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : [ "A", "B", "E" ], "Name" : "Chris" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : [ "C", "D", "B" ], "Name" : "David" }
以下是在MongoDB中创建多个数组的单个数组的查询-
> db.demo289.aggregate({ $unwind : "$Section" } );
这将产生以下输出-
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "A", "Name" : "Chris" } { "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "B", "Name" : "Chris" } { "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "E", "Name" : "Chris" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "C", "Name" : "David" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "D", "Name" : "David" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "B", "Name" : "David" }