【问题标题】:Mongoose count certain element in an embedded documents arrayMongoose 计算嵌入文档数组中的某些元素
【发布时间】:2017-02-17 12:38:11
【问题描述】:

我正在使用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);

如何计算 Draw 的门票(DrawSchema 中的门票字段)中某个用户对象 ID(TicketSchema 中的用户字段)的嵌入文档? 我想计算一个用户的单次抽奖的票。

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以使用聚合框架,利用 $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);
    });
    

    【讨论】:

    • 很好的答案。我得到了我需要的信息,但我只想汇总具有给定 ID 的平局。
    • 我得到的响应是所有抽奖 id 及其对 userId 的计数。我只想聚合单个绘制 id
    • @AlexB 你需要一个 $match 管道查询来过滤你的文档,正如我在上面的更新中所展示的那样。
    • FWIW,大多数基于云的 Mongodb 平台,例如 Heroku 提供的每个基于云的解决方案,还不支持 mongo 版本 3.4,因此 $filter 命令不起作用跨度>
    【解决方案2】:

    您可以像任何其他查询对象一样传递.count() 深度参数:

    Draw.count({'tickets.user._id' : userId}, console.log);
    

    确保 userId 变量是 ObjectId。如果是字符串,请执行以下操作:

    const ObjectId = require('mongoose').Types.ObjectId;
    let userId = new ObjectId(incomingStringId);
    

    【讨论】:

    • 这不适用于特定的平局。我会尝试添加“_id”:drawId
    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2011-09-01
    • 1970-01-01
    • 2018-11-28
    • 2019-04-19
    • 1970-01-01
    • 2023-04-05
    • 2021-12-16
    相关资源
    最近更新 更多