1

我有一个复杂的对象,这是一个简化版本,只是为了展示我首先要做什么......

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

好的,所以基本上我想做的是返回一个没有作者的书籍列表。这不是实际项目,我只是将其用作一个简单的示例,但假设我想查询所有书籍,或者可能是 200 本书。在这个列表中,我不希望每本书都包含所有作者,作者子文档中可能有数百个条目。

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

4

1 回答 1

3

您可以通过向命令提供projection参数来执行此操作find

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})   
于 2013-10-15T19:44:17.537 回答