如何僅使用 MongoDB 聚合獲取陣列中的值?


讓我們建立一個包含文件的集合——

> db.demo411.insertOne(
...    {
...       "Information" : [
...          {
...             "Name1" : "Chris",
...             "Name2" : "David"
...          },
...          {
...             "Name1" : "John",
...             "Name2" : "John"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70f19715dc524f70227682")
}

藉助 find() 方法顯示集合中的所有文件——

> db.demo411.find();

這將生成以下輸出——

{ "_id" : ObjectId("5e70f19715dc524f70227682"), "Information" : [ { "Name1" : "Chris", "Name2" : "David" }, { "Name1" : "John", "Name2" : "John" } ] }

以下是僅獲取陣列中值所用的查詢——

> db.demo411.aggregate(
...    [
...       {$project : {
...          _id : 0,
...          Information : {$map : {input : "$Information", as : "out", in : ["$$out.Name1", "$$out.Name2"]}}
...          }
...       }
...    ]
... )

這將生成以下輸出——

{ "Information" : [ [ "Chris", "David" ], [ "John", "John" ] ] }

更新於: 03-04-2020

848 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.