如何将 mongod 数据库查询更改为聚合

How to change the mongod db query to aggregation

  1. 我有三个查询,现在我想将其更改为 MongoDB 聚合 下面是代码:

          db.mycollection.count({$and:[$requestB:{$exists:false},[$requestC:{$exists:false}]})
          db.mycollection.count({requestB:{$exists:true}})
          db.mycollection.count({requestC:{$exists:true}})
    
  2. 现在我想将此代码更改为聚合,但它不起作用

       db.mycollection.aggregate( [
     { $group: {
         '_id' : { user_id: '$user_id'},
         requestA_count: { $sum: {
             $cond: [ {$and: [{$eq: ["$requestB", null]}, {$eq: ["requestC", null]}}}, 1, 0 ]
         } },
         requestB_count: { $sum: {
             $cond: [ {requestB:{'$exists':true}}, 1, 0 ]
         } },
         requestC_count: { $sum: {
             $cond: [ {requestC:{'$exists':true}}, 1, 0 ]
         } },
     } },
     { $project: {
         _id: 0,
         user_id: '$_id.user_id',
         requestA_count: 1,
         requestB_count: 1,
         requestC_count: 1
     } }
     ] );
    

您可以在 $group

中使用 $type 而不是 $exists
db.collection.aggregate([
  {
    $group: {
      "_id": { user_id: "$user_id" },
      requestA_count: {
        $sum: {
          $cond: [
            {
              $and: [
                { $ne: [{$type: "$requestA"}, "missing"] }, 
                { $eq: [{$type: "$requestB"}, "missing"] }, 
                { $eq: [{$type: "$requestC"}, "missing"] }
              ]
            },  // you need to close bracket here not below
            1, 0
          ]
        }
      },
      requestB_count: {
        $sum: { $cond: [{ $ne: [{ $type: "$requestB" }, "missing"] }, 1, 0] }
      },
      requestC_count: {
        $sum: { $cond: [{ $ne: [ { $type: "$requestC" }, "missing" ] }, 1, 0] }
      }
    }
  },
  {
    $project: {
      _id: 0,
      user_id: "$_id.user_id",
      requestA_count: 1,
      requestB_count: 1,
      requestC_count: 1
    }
  }
])

Playground