【问题标题】:How to find array elements with Mongoose?如何使用 Mongoose 查找数组元素?
【发布时间】:2017-12-05 23:13:57
【问题描述】:

我在 Mongoose 模型中有一个数组作为子文档,定义如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = Schema({
    author: { type: Schema.Types.ObjectId, ref: 'Author' },
    pages: [{
        number: Number, 
        type: { type: String, enum: ['boring', 'fun']},
    }]
});

module.exports = mongoose.model('Book', schema);

现在我想获取某个作者在所有书籍中的'fun' 页总数。我发现许多类似的问题(和答案)讨论了如何在这种情况下找到带有有趣页面的Books,但是我想获得所有有趣页面的数组,或者至少是该数组的长度,但如果可能的话我会喜欢得到数组本身。我该怎么做?

谢谢,

【问题讨论】:

  • 尝试(未经测试,如果正确将添加为答案): Book.aggregate( { $unwind: "$pages" }, { $group: { _id: "$pages.type", count : { $sum: 1 } }} )
  • @nadavvadan 谢谢!似乎它正在工作。但我刚刚意识到我需要再过滤一次,而不是所有书籍,我只需要从某个作者的书籍中进行选择。如果问的不多,能否请您也补充一下? :) 再次感谢,
  • 试试这个:Book.aggregate( {$match: {author: ObjectId("12-bytes-of-hex")} }, { $unwind: "$pages" }, { $group : { _id: "$pages.type", count: { $sum: 1 } }})

标签: arrays node.js mongodb mongoose mongoose-schema


【解决方案1】:

我相信,除了语法,这是不言自明的:

Book.aggregate(

    { 
        $match: {
            author: ObjectId("12-bytes-of-hex")
        }
     },

    { $unwind: "$pages" },

    { $group: {
        _id: "$pages.type",
        count: { $sum: 1 }
    }}
)

【讨论】:

  • 我没看懂,这个是怎么根据type=='fun'过滤页面的?
  • 它并没有做到这一点;它按页面类型对页面进行分组,并对每个组进行计数。您也可以使用 mongo 的 mapReduce 框架来获取“有趣”页面类型的页面计数,但我相信上述解决方案更简单。
猜你喜欢
  • 2014-05-21
  • 2020-07-08
  • 2016-05-28
  • 1970-01-01
  • 2014-12-29
  • 2019-08-09
  • 2022-11-25
  • 2014-01-31
  • 2023-03-08
相关资源
最近更新 更多