使用嵌套对象的过滤字段进行查询

发布于 2024-12-14 19:54:29 字数 557 浏览 2 评论 0原文

可以说我有一个文档,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-12-21 19:54:29

您的查询

 books.all[0].chapters.only(:title)[0].sections 

会选择 books.all 上所有章节嵌入文档的书籍,因此在章节后使用“only”是没有意义的。如果章节作为单独的文档并且具有 has_many 关系而不是 embeds_many ,则您的查询可以工作

所以您必须在书籍文档上使用“only”

 books.only('chapters.title').all[0].chapters.sections 

your query

 books.all[0].chapters.only(:title)[0].sections 

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

 books.only('chapters.title').all[0].chapters.sections 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文