2
  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
     } }
     ] );
    
4

1 回答 1

0

您可以使用$type代替$existsinside $group

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

操场

于 2020-09-10T05:18:37.830 回答