node.js - Mongoose 计算嵌入文档数组中的某些元素

标签 node.js mongodb mongoose aggregation-framework mongodb-aggregation

我正在使用mongoose 4.6.3

我有以下架构:

var mongoose = require('mongoose');
var User = require('./User');

var TicketSchema = new mongoose.Schema({
    user : { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
},
{
    timestamps: true
});

var DrawSchema = new mongoose.Schema({
  ...
  max_ticket_per_user : { type : Number, required: true },
  tickets: [TicketSchema]
});

module.exports = mongoose.model('Draw', DrawSchema);

如何统计抽奖门票(DrawSchema 中的门票字段)中某个 User ObjectId(TicketSchema 中的 user 字段)的嵌入文档? 我想统计一个用户单次抽奖的票数。

改变我的架构设计会更好吗?

谢谢

最佳答案

您可以利用 $filter 的优势来使用聚合框架。 $size 运算符来获取过滤后的数组,其中的元素分别与用户 ID 及其大小匹配,随后将为您提供计数。

对于单次抽奖,请考虑添加 $match 管道运算符作为初始步骤,使用 _id 查询来过滤集合中的文档。

考虑运行以下聚合管道以获得所需的结果:

Draw.aggregate([
    { "$match": { "_id": drawId } },
    {
        "$project": {
            "ticketsCount": {
                "$size": {
                    "$filter": {
                        "input": "$tickets",
                        "as": "item",
                        "cond": { "$eq": [ "$$item.user", userId ] }
                    }
                }
            }
        }
    }
]).exec(function(err, result) {
    console.log(result);
});

关于node.js - Mongoose 计算嵌入文档数组中的某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935428/

相关文章:

javascript - 如何确保node js在异步调用后返回数据?

node.js - 从mongodb中的多个集合中获取数据

node.js - mongoose findByIdAndDelete/findOneAndRemove 不删除

mongodb - GeoNear Mongoose 和 2d 索引

node.js - MongoError : Invalid Operation, 没有批量操作

javascript - 将 Promise 与 mongoose 函数一起使用

javascript - 使用带有sequelizejs的日期来统计客户今年的订单

node.js - 通过 final方法发送所有路由

mongodb - 在 MongoDb @CreatedBy 使用 springBoot 获取 null

c# - 使用 NoRM 在 MongoDB 中的一个集合中存储多种类型的对象