如何获取每个文档的数组元素中特定项目的出现总数

时间:2019-10-24 07:51:06

标签: node.js mongodb express mongoose

我正在为我的Express应用程序实现偏爱/不偏爱功能,但是我对如何计算该帖子已被收藏的总数有疑问。

假设我有此配方结构

Future.wait

和用户架构

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

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

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 });

我查找了答案,但找不到答案。我是mongodb和nodejs的新手,请耐心等待。我看到的一些答案与聚合有关。

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

[{
  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

1 个答案:

答案 0 :(得分: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中签出正在运行的代码。