【问题标题】:Count the number of occurence of a nested field计算嵌套字段的出现次数
【发布时间】:2018-12-30 21:00:56
【问题描述】:

我正在尝试计算嵌套字段中具有匹配条件的文档数。

我的架构定义如下:

let userSchema = new Schema({
  //...
  interests: [{
    type: Schema.Types.ObjectId,
    ref: 'Interests'
  }],
  //...
});

let interestSchema = new Schema({
  id: ObjectId,
  name: {
    type: String,
    required: true
  },
  //...
});

计数必须反映用户选择同名兴趣的次数。

例如,我在以下文档中必须有一个结果为 2 的兴趣“编码”:

{
  //Other Fields of user 1
  "interests": [
     {
       "id": "XXX"
       "name": "coding"
     }, 
     {
       "id": "YYY"
       "name": "surfing"
     }]
}

{
  //Other Fields of user 2
  "interests": [
     {
       "id": "ZZZ"
       "name": "coding"
     }
   ]
}

我查看了countDocuments 方法,但它似乎不允许这种计数。


编辑 + 第一个解决方案:

这就是我设法解决的方法:

const res = await UserModel.aggregate([
  {
    $unwind: '$interests'
  },
  {
    $lookup: {
      from: "interests",
      localField: "interests",
      foreignField: "_id",
      as: "interests"
    }
  },
  {
    $match:{
      "interests.name": name
    }
  },
  {
    $count: "count"
  }
]);
return res[0].count;

兴趣是一个引用类型,除非我通过lookup 阶段,否则我无法查询其名称。我不确定这是否是一个关于性能的好解决方案,因为unwind 阶段必须通过数据库的所有用户并为他们的每个兴趣创建一个新元素。这就是为什么我不将其发布为答案的原因

【问题讨论】:

  • 尝试使用聚合来展开兴趣和按名称分组。如果您有任何尝试和错误,请展示您的尝试和错误。
  • 使用model.where({ 'interests.name': 'coding' }).count();
  • 一个简单的计数查询就可以做到db.collection.count({ interests: { $elemMatch: { name: "coding" } } })...stackoverflow.com/questions/50210367/…

标签: node.js mongodb mongoose


【解决方案1】:

要使用elemMatch,我必须更改架构以便将Interest 嵌入User 而不是引用它:

let userSchema = new Schema({
  //...
  interests:  [InterestSchema],
  //...
});

let InterestSchema = new Schema({
  id: ObjectId,
  name: {
    type: String,
    required: true
  },
  //...
});

这就是我使用elemMatch的方式:

const count = UserModel
  .where('interests').elemMatch( interest => {
    interest.where({ name: name });
  })
  .count();

正如我在问题中提到的,聚合 method 有效,但我不确定它的性能,因为我使用的是引用数组而不是子文档,这就是为什么我必须更改我的集合的架构

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多