简体   繁体   中英

Return document without subdocuments in MongoDB

I have a complex object, here is a simplified version just to show what I'm trying to do first...

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

Ok, so basically what I want to do is return a list of books without the authors. This isn't the actual item, I'm just using it as a simple example, but lets' just say I want to query all books, or maybe 200 books. In this list, I don't want each of the book to contain all authors, there could be hundreds of entries in the author sub document.

I want to keep them together still, if that's possible, instead of using references only. So basically, can I get all books without getting authors as well using this schema?

You can do this by providing a projection argument to the find command:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM