【问题标题】:Return document without subdocuments in MongoDB在 MongoDB 中返回没有子文档的文档
【发布时间】:2013-10-16 03:44:17
【问题描述】:

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

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

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

如果可能的话,我想将它们保持在一起,而不是仅使用引用。所以基本上,我可以在不获取作者的情况下使用此模式获取所有书籍吗?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您可以通过向find 命令提供projection argument 来做到这一点:

    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})   
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2021-06-17
      • 2013-05-06
      • 2016-04-26
      • 2017-04-02
      • 2014-09-26
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多