使用嵌套对象的过滤字段进行查询
可以说我有一个文档,
book: {name: "book",
"chapters":[{title: "Chapter I",
"sections":[{},{}]
}, {...}
]}
我如何获取带有嵌入对象章节的书籍对象,但每个章节不应包含嵌套的“部分”(但应包含其他属性,如标题):
book: {name: "Book",
"chapters":[{title: "Chapter I"
}, {...}
]}
我应该如何使用 Mongo 进行查询driver 和 Mongoid (或 Mongomapper)?
我用 mongoid 尝试过:
books.all[0].chapters.only(:title)[0].sections # it still works, though I expect sections to be nil
lets say I've got a document
book: {name: "book",
"chapters":[{title: "Chapter I",
"sections":[{},{}]
}, {...}
]}
I what to get book object with embedded object chapters but each chapter should not contain nested "sections" (but should contain other attributes, like title):
book: {name: "Book",
"chapters":[{title: "Chapter I"
}, {...}
]}
How should I make a query using Mongo driver and Mongoid (or Mongomapper)?
I tried it with mongoid:
books.all[0].chapters.only(:title)[0].sections # it still works, though I expect sections to be nil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的查询
会选择 books.all 上所有章节嵌入文档的书籍,因此在章节后使用“only”是没有意义的。如果章节作为单独的文档并且具有 has_many 关系而不是 embeds_many ,则您的查询可以工作
所以您必须在书籍文档上使用“only”
your query
picks the books with all its chapter embedded documents on books.all, so there is no meaning to use 'only' after chapters. Your query can work if the chapters as a separate documents and got a has_many relationship instead embeds_many
So you have to use 'only' like this on books document