【问题标题】:How to get the total number of occurences of a specific item in every document's array element如何获取每个文档数组元素中特定项目的出现总数
【发布时间】:2019-10-29 06:55:48
【问题描述】:

我正在为我的快递应用程序实现收藏/取消收藏功能,但我在如何计算帖子被收藏的总数方面遇到了问题。

假设我有这个食谱架构

RecipeSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 30
  },
  description: {
    type: String,
    default: ''
  },
  favoritesCount: {
    type: Number,
    default: 0
  }
})

和用户架构

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    minlength: 8,
    required: true,
    unique: true
  },
  fullname: {
    type: String,
    maxlength: 40,
    minlength: 4,
    required: true
  },
  password: {
    type: String,
    required: true,
    minlength: 8
  }
  favorites: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Recipe'
  }]
}, { timestamps: true });

现在假设我有这个用户文档, 如何计算每个用户文档的收藏夹数组中存在的 Recipe ID (5daef9a2761d4b1668214dbc) 总数?

[{
  username: 'john123',
  email: 'john@test.com',
  favorites: ['5daef9a2761d4b1668214dbc']
}, {
  username: 'jane75',
  email: 'jane@test.com',
  favorites: []
}, {
  username: 'johnwick',
  email: 'johnwick@test.com',
  favorites: ['5daef9a2761d4b1668214dbc']
}]

// Should yield 2

我查找了答案,但找不到。我是 mongodb 和 nodejs 的新手,所以请多多包涵。我看到的一些答案与聚合有关。

到目前为止,我已经尝试过这段代码。但它只返回用户文档的数量。

const User = require('./User') // the User model

RecipeSchema.methods.updateFavoriteCount = function() {
  return User.count({
    favorites: {
      $in: [this._id]
    }
  }).then((count) => {
    this.favoritesCount = count;
    return this.save();
  });
};

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以在 aggregation$size 的帮助下完成。更多详情,请参阅此document

    您的查询

    db.collection.aggregate([
      {
        $project: {
          username: 1,
          email: 1,
          totalFavritesCount: {
            $cond: {
              if: {
                $isArray: "$favorites"
              },
              then: {
                $size: "$favorites"
              },
              else: "NA"
            }
          }
        }
      }
    ])
    

    结果

    [
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "email": "john@test.com",
        "totalFavritesCount": 1,
        "username": "john123"
      },
      {
        "_id": ObjectId("5a934e000102030405000001"),
        "email": "jane@test.com",
        "totalFavritesCount": 0,
        "username": "jane75"
      },
      {
        "_id": ObjectId("5a934e000102030405000002"),
        "email": "johnwick@test.com",
        "totalFavritesCount": 1,
        "username": "johnwick"
      }
    ]
    

    你也可以在这个link查看运行代码。

    【讨论】:

    • 请不要回滚任何编辑,Pushprajsinh。
    • 请注意,此处不允许投票乞讨,版主将支持任何试图恢复此类更改的编辑。让人们对答案进行有机投票要好得多 - 如果他们很好,他们会自然而然地被投赞成票。
    • 但有时 OP 不会应用答案。无论如何,会小心,不会要求应用。谢谢你纠正我。 @halfer
    • OP 没有义务对答案进行投票(甚至回复)。也就是说,可以添加评论以询问您的解决方案是否有帮助。如果您怀疑 OP 不知道如何接受答案(例如,他们接受的答案为零或很少),那么您可以将他们指向 Stack Overflow 文档。但是不要把这种东西放在答案中——这绝对是只评论的材料。
    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2019-09-20
    • 2015-01-26
    • 2018-09-20
    相关资源
    最近更新 更多