2017-11-18 26 views
0

我有MongoDB的查詢問題值子查詢替換包裹在列表中collaction一種在集合體B MongoDB的關鍵

有2個集合在我的數據庫,名稱statusmenu

status主鍵_id對於買表的值menu收集

外鍵對於status集合:

{ 
    "_id": "green", "description": "running" 
} 
{ 
    "_id": "yellow", "description": "prepareing" 
} 
{ 
    "_id": "black", "description": "closing" 
} 
{ 
    "_id": "red", "description": "repairing" 
} 

對於menu集合:

{ 
    "name": "tony", 
    "bought": [ 
     { 
      "notebook": "green" 
     }, 
     { 
      "cellphone": "red" 
     } 
    ] 
} 
{ 
    "name": "andy", 
    "bought": [ 
     { 
      "fan": "black" 
     } 
    ] 
} 

我怎樣才能查詢得到以下答案嗎?

(只需更換description_id

{ 
    "name": "tony", 
    "bought": [ 
     { 
      "notebook": "running" 
     }, 
     { 
      "cellphone": "repairing" 
     } 
    ] 
} 

是它的NoSQL子查詢問題?我如何使用關鍵詞來谷歌?

回答

1

下面是使用聚合版本:

我們先從$unwind階段提取一個單獨的行

然後,$objectToArray各買正常化買場。

然後我們可以執行$lookup加入狀態。

然後我們使用$group按名稱

而且$arrayToObject重新集結到復位買了非規範化的風格

> db.menu.find() 
{ "_id" : ObjectId("5a102b0b49b317e3f8d6268b"), "name" : "tony", "bought" : [ { "notebook" : "green" }, { "cellphone" : "red" } ] } 
{ "_id" : ObjectId("5a102b0b49b317e3f8d6268c"), "name" : "andy", "bought" : [ { "fan" : "black" } ] } 
> db.status.find() 
{ "_id" : "green", "description" : "running" } 
{ "_id" : "yellow", "description" : "prepareing" } 
{ "_id" : "black", "description" : "closing" } 
{ "_id" : "red", "description" : "repairing" } 
> db.menu.aggregate([ 
{$unwind: '$bought'}, 
{$project: {name: 1, bought: {$objectToArray: '$bought'}}}, {$unwind: '$bought'}, 
{$lookup: {from: 'status', localField: 'bought.v', foreignField: '_id', as: "status"}}, 
{$project: {name: 1, bought: ["$bought.k", { $arrayElemAt: ["$status.description", 0]}]}}, 
{$addFields: {b: {v: {$arrayElemAt: ['$bought', 1]}, k: { $arrayElemAt: ['$bought', 0]}}}}, 
{$group: {_id: { name: '$name', _id: "$_id"}, b: {$push: "$b"}}},  
{$project: {_id: "$_id._id", name: "$_id.name", bought: {$arrayToObject: "$b"}}} 
]) 
{ "_id" : ObjectId("5a102b0b49b317e3f8d6268c"), "name" : "andy", "bought" : { "fan" : "closing" } } 
{ "_id" : ObjectId("5a102b0b49b317e3f8d6268b"), "name" : "tony", "bought" : { "notebook" : "running", "cellphone" : "repairing" } } 

我認爲它可以在simplier的方式進行,但我不知道如何(我很高興知道)。

+0

謝謝!它對我有用。我也想知道一個更簡單的答案。 –