2017-05-28 54 views
1

我有一個關於查詢嵌套文檔的問題。我試圖搜索,但沒有回答我的問題,或者我可能忽略了它。我有結構是這樣的:如何從所有文檔中僅返回數組的嵌套文檔

{ 
    "_id" : ObjectId("592aa441e0f8de09b0912fe9"), 
    "name" : "Patrick Rothfuss", 
    "books" : [ 
    { 
     "title" : "Name of the wind", 
     "pages" : 400, 
     "_id" : ObjectId("592aa441e0f8de09b0912fea") 
    }, 
    { 
     "title" : "Wise Man's Fear", 
     "pages" : 500, 
     "_id" : ObjectId("592aa441e0f8de09b0912feb") 
    }, 
    }, 
    { 
    "_id" : ObjectId("592aa441e0f8de09b0912fe9"), 
    "name" : "Rober Jordan", 
    "books" : [ 
    { 
     "title" : "The Eye of the World", 
     "pages" : 400, 
     "_id" : ObjectId("592aa441e0f8de09b0912fea") 
    }, 
    { 
     "title" : "The Great Hunt", 
     "pages" : 500, 
     "_id" : ObjectId("592aa441e0f8de09b0912feb") 
    } 
    }, 

而且我想查詢的所有在作者的整個總彙名單 - 是這樣的:

"books" : [ 
    { 
     "title" : "The Eye of the World", 
     "pages" : 400, 
     "_id" : ObjectId("592aa441e0f8de09b0912fea") 
    }, 
    { 
     "title" : "The Great Hunt", 
     "pages" : 500, 
     "_id" : ObjectId("592aa441e0f8de09b0912feb") 
    }, 
    { 
     "title" : "Name of the wind", 
     "pages" : 400, 
     "_id" : ObjectId("592aa441e0f8de09b0912fea") 
    }, 
    { 
     "title" : "Wise Man's Fear", 
     "pages" : 500, 
     "_id" : ObjectId("592aa441e0f8de09b0912fea") 
    }] 
+0

你到底在問什麼?是如何從數組中「提取」所有嵌入式文檔並簡單地返回這些結果?這裏「同名」是什麼意思? –

+0

相同elemnt名稱我猜 - **書**?在db集合中提取每個** book **的列表。不知道如何更好地描述它。 – LadaWalker

回答

0

可以使用.aggregate()做到這一點,主要爲$unwind管道運營商:

在現代的MongoDB 3.4及以上,你可以串聯使用與$replaceRoot

Model.aggregate([ 
    { "$unwind": "$books" }, 
    { "$replaceRoot": { "newRoot": "$books" } } 
],function(err,results) { 

}) 

在早期版本中,你與$project指定各個領域:

Model.aggregate([ 
    { "$unwind": "$books" }, 
    { "$project": { 
    "_id": "$books._id", 
    "pages": "$books.pages", 
    "title": "$books.title" 
    }} 
],function(err,results) { 

}) 

所以$unwind是你用什麼來解構或「denormalise」進行處理的數組項。實際上,這會爲陣列的每個成員創建整個文檔的副本。

該任務的其餘部分是關於僅返回數組中存在的字段。

雖然這不是一個明智的做法。如果您的意圖是僅返回嵌入在文檔數組中的內容,那麼最好將該內容放入單獨的集合中。

它的性能要好得多,用集合框架從集合中分離出所有文檔,僅僅從數組中列出這些文檔。

+0

不錯,那正是我的意思。謝謝。 – LadaWalker

0

根據上述說明,請嘗試在MongoDB shell中執行以下查詢。

db.collection.aggregate(

    // Pipeline 
    [ 
     // Stage 1 
     { 
      $unwind: "$books" 
     }, 

     // Stage 2 
     { 
      $group: { 
       _id:null, 
       books:{$addToSet:'$books'} 
      } 
     }, 

     // Stage 3 
     { 
      $project: { 
       books:1, 
       _id:0 
      } 
     }, 

    ] 

); 
相關問題