mongoose 获取匹配不同条件的文档计数

iqih9akk  于 2022-11-24  发布在  Go
关注(0)|答案(2)|浏览(138)

我有收藏:bookSchema为:

[
    {
      _id: ObjectId("637d05dc32428ed75ea08d09"),
      book_details: {
        book_name: "random123",
        book_auth: "Amber"
      }
    },
    {
      _id: ObjectId("637d0673ce0f17f6c473dee2"),
      book_details: {
        book_name: "random321",
        book_auth: "Amber"
      }
    },
    {
      _id: ObjectId("637d069a3d597c8458ebe4ec"),
      book_details: {
        book_name: "random676",
        book_auth: "Amber"
      }
    },
    {
      _id: ObjectId("637d06c05b32d503007bcb54"),
      book_details: {
        book_name: "random999",
        book_auth: "Saurav"
      }
    }
  ]

所需的O/P显示为:

{
  score_ambr: 3,
  score_saurabh: 1
}

为此我试着说:

db.bookSchema.aggregate([
  {
    "$group": {
      "_id": {
        "$eq": [
          "$book_details.book_auth",
          "Amber"
        ]
      },
      "score_ambr": {
        "$sum": 1
      }
    },

  },
  {
    "$group": {
      "_id": {
        "$eq": [
          "$book_details.book_auth",
          "Saurav"
        ]
      },
      "score_saurabh": {
        "$sum": 1
      }
    },

  }
])

我尝试使用$group to,因为我想将所有匹配的文档归为一组,并使用$count给予匹配文档的计数,但它似乎不起作用,并给出O/P为
操作员:

[
  {
    "_id": false,
    "score_sau": 2
  }
]

MongoDBPlayground:https://mongoplayground.net/p/cZ64KwAmwlv

wmtdaxz3

wmtdaxz31#

我不知道示例中31是什么意思,但如果我理解正确,您可以尝试以下查询:
这里的技巧是使用$facet在聚合中创建“两种方式”,一种是按Amber过滤,另一种是按Saurav过滤。
然后,在筛选值时,您只需要知道生成的数组的大小。

db.collection.aggregate([
  {
    "$facet": {
      "score_ambr": [
        {
          "$match": {
            "book_details.book_auth": "Amber"
          }
        }
      ],
      "score_saurabh": [
        {
          "$match": {
            "book_details.book_auth": "Saurav"
          }
        }
      ]
    }
  },
  {
    "$project": {
      "score_ambr": {
        "$size": "$score_ambr"
      },
      "score_saurabh": {
        "$size": "$score_saurabh"
      }
    }
  }
])

示例here
请注意,这样可以避免使用$group

r3i60tvu

r3i60tvu2#

它看起来像你想要的是两个组两次并从book_details.book_auth创建一个动态键:

db.bookSchema.aggregate([
  {$group: {_id: "$book_details.book_auth", count: {$sum: 1}}},
  {$group: {
      _id: 0, 
      data: {$push: {
          k: {$concat: ["score_", {$toLower: "$_id"}]},
          v: {$sum: "$count"}
      }}
  }},
  {$replaceRoot: {newRoot: {$arrayToObject: "$data"}}}
])

了解它在playground example上的工作原理

相关问题