2017-05-28 48 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 
      } 
     }, 

    ] 

); 
相关问题