Mongodb 用HAVING子句选择COUNT

Mongodb 用HAVING子句选择COUNT,mongodb,mongodb-query,Mongodb,Mongodb Query,这是我的意见: {"_id": "phd/Klink2006","type": "Phd", "title": "IQForCE - Intelligent Query (Re-)Formulation with Concept-based Expansion", "year": 2006, "publisher": "Ver

这是我的意见:

 {"_id": "phd/Klink2006","type": "Phd", "title": "IQForCE - Intelligent Query (Re-)Formulation with Concept-based Expansion", "year": 2006, "publisher": "Verlag Dr. Hut, M?nchen", "authors": ["Stefan Klink"], "isbn": ["3-89963-303-2"]}
我想数一数作者少于3位的书。我怎样才能做到这一点?

  • $group
    按null,如果作者的大小小于3,请检查条件,然后计数1,否则为0

  • $group
    按null,如果作者的大小小于3,请检查条件,然后计数1,否则为0

您可以使用操作员(这将返回所有文档)

您可以使用操作员(这将返回所有文档)


从MongoDB 4.4开始,$where不再支持范围为(BSON类型15)的不推荐的BSON类型JavaScript代码。$where运算符仅支持BSON类型字符串(BSON类型2)或BSON类型JavaScript(BSON类型13)。自MongoDB 4.2.1以来,使用作用域为$where的BSON类型JavaScript已被弃用。从MongoDB 4.4开始,$where不再支持作用域为$where的弃用BSON类型JavaScript代码(BSON类型15)。$where运算符仅支持BSON类型字符串(BSON类型2)或BSON类型JavaScript(BSON类型13)。自MongoDB 4.2.1以来,使用作用域为$where的BSON类型JavaScript已被弃用。
db.collection.aggregate([
  {
    $group: {
      _id: null,
      count: {
        $sum: {
          $cond: [
            { $lt: [{ $size: "$authors" }, 3] },
            1,
            0
          ]
        }
      }
    }
  }
])
db.collection.find({
  "$where": "this.authors.length < 3"
});
db.collection.aggregate([
  {
    "$match": {
      "authorsLength": {
        "$lt": 3
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])