如何從 MongoDB 的物件陣列中獲取項?


若要從物件陣列中獲取項,可以使用 aggregate()。我們建立一個包含文件的集合 −

> db.demo459.insertOne(
... { "_id" : 1,
... "Information" : [
...    {
...       "Name" : "Chris",
...       "_id" : new ObjectId(),
...       "details" : [
...          "HR"
...       ]
...    },
... {
...
...    "Name" : "David",
...    "_id" : new ObjectId(),
...    "details" : [
...       "Developer"
...    ]
... },
... {
...
...    "Name" : "Bob",
...    "_id" : new ObjectId(),
...    "details" : [
...       "Account"
...    ]
... }
... ]
... }
... )
{ "acknowledged" : true, "insertedId" : 1 }

使用 find() 方法顯示集合中的所有文件 −

> db.demo459.find();

這會生成以下輸出 −

{ "_id" : 1, "Information" : [ { "Name" : "Chris", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95c9"),
"details" : [ "HR" ] }, { "Name" : "David", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95ca"),
"details" : [ "Developer" ] }, { "Name" : "Bob", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95cb"),
"details" : [ "Account" ] } ] }

以下是 MongoDB 中從物件陣列獲取項的查詢 −

> db.demo459.aggregate([
...    { $unwind: '$Information' },
...    { $unwind: '$Information.details' },
...    { $match: { 'Information.Name': { $in: ["Chris","Bob"]} } },
...    { $group: { _id: null, detailList: { $addToSet: '$Information.details' } } },
... ])

這會生成以下輸出 −

{ "_id" : null, "detailList" : [ "Account", "HR" ] }

更新日期:2020 年 5 月 11 日

842 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.