2017-10-13 181 views
-1

例如,我想在我的数据库中列出所有注册的发布者。我将如何做到这一点与此嵌入式文件:如何在所有文档中查询所有不同的嵌入式文档

{ 
    title: "MongoDB: The Definitive Guide", 
    author: [ "Kristina Chodorow", "Mike Dirolf" ], 
    published_date: ISODate("2010-09-24"), 
    pages: 216, 
    language: "English", 
    publisher: { 
       name: "O'Reilly Media", 
       founded: 1980, 
       location: "CA" 
      } 
} 

我想检索独立于其书籍的所有DISTINCT出版商。如果我使用这样的文档参考会更容易:

{ 
    name: "O'Reilly Media", 
    founded: 1980, 
    location: "CA", 
    books: [123456789, 234567890, ...] 
} 

{ 
    _id: 123456789, 
    title: "MongoDB: The Definitive Guide", 
    author: [ "Kristina Chodorow", "Mike Dirolf" ], 
    published_date: ISODate("2010-09-24"), 
    pages: 216, 
    language: "English" 
} 

但我不想这样做。

+1

您可以查询使用'db.collection_name.find让所有的出版商({},{出版社:1}) '。对于不同的发布商,您可以尝试'db.collection_name.distinct(“publisher”)' – Veeram

+0

我认为这是我想要的 – jvitoroc

+0

但是,distinct的性能呢?它会检查每本书,甚至是其出版商已经检索到的书籍。我对吗? – jvitoroc

回答

0

您是否希望获得所有出版商的支持?你有没有尝试MongoDB聚集$项目管道?

喜欢的东西:

db.collection.aggregate([ 
    { 
     $project: { 
      "_id": 0, //This line is optional 
      "publisher": 1 
     } 
    } 
]) 
0

你也可以试试这个:

db.getCollection('yourCollectionName').aggregate([ 
{ 
    $group: { 
     _id: "$publisher" 
     } 
} 
]) 
相关问题