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

更新時間: 31-Mar-2020

222 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.