2013-10-15 34 views
1

子文档返回文档我有一个复杂的对象,这里是一个简化版本,只是为了显示我想要第一个做...没有MongoDB中

books: [{ 
title: 'book 1', 
    authors: [ 
    { name: 'jim' }, 
    { name: 'bob' }, 
    ] 
}, { 
    title: 'book 2', 
    authors: [ 
    { name: 'steve' }, 
    { name: 'joe' }, 
    ] 
}]; 

好了,基本上就是我想要做的是返回没有作者的书籍清单。这不是实际的东西,我只是用它作为一个简单的例子,但让我们只是说我想查询所有的书籍,或者可能是200本书。在这个列表中,我不希望每本书都包含所有的作者,在作者子文档中可能有数百个条目。

我想保持它们仍然在一起,如果这是可能的,而不是仅使用引用。所以基本上,我可以在不使用这个模式的情况下获得所有书籍吗?

回答

3

可以通过提供一个projection argumentfind命令做到这一点:

db.bookshelves.insert({ 
    "type": "wood", 
    "books": [ 
     { 
      "title": "book 1", 
      "authors": [ 
       {"name": "jim"}, 
       {"name": "bob"} 
       ] 
      }, 
     { 
      "title": "book 2", 
      "authors": [ 
       {"name": "steve"}, 
       {"name": "joe"} 
       ] 
      } 
     ] 
    } 
) 

# Returns the whole document 
db.bookshelves.find({"type": "wood"}) 

# Omits the "author" field of each book: 
db.bookshelves.find({"type": "wood"}, {"books.authors": 0}) 
+0

非常感谢,这对我的作品。 –