【问题标题】:Mongodb query, result only specific elements into array of objectsMongodb查询,仅将特定元素结果到对象数组中
【发布时间】:2016-01-06 14:53:02
【问题描述】:

我有一个问题导致我在 mongodb 中查询。

我有一组这样的文档:https://github.com/pedrualves/document/blob/master/school.js

我可以毫无问题地搜索此文档 “页数”:32

但是,我无法显示这样的结果:

{
"book": [
 {
  "pages": 32,
  "title": "a"
 },
 {
  "pages": 32,
  "title": "c"
 },
 {
  "pages": 32,
  "title": "d"
 }
]
}

有人可以帮我解决这个问题吗?

谢谢

【问题讨论】:

    标签: arrays json mongodb object jsonresult


    【解决方案1】:

    使用 Unwind 从聚合框架解决了这个问题。 所以我可以拆分数组、分组和过滤器。

    db.'collection_name'.aggregate([
    { $unwind : "$students" },
    { $unwind : "$students.class" },
    { $unwind : "$students.class.book" },
    {$match:{"students.class.book.pages":{$in:[32]}}},
    {$group:
    {
    _id:'$students.name',
    teste:{$push:'$students.class.book'}
    }
    }
    ])
    

    另外,可以使用操作符$redact

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-13
      相关资源
      最近更新 更多