在 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" }
广告