查询MongoDB中的多个计数

查询MongoDB中的多个计数,mongodb,match,aggregate,Mongodb,Match,Aggregate,我是MongoDB的新手,在解决这个问题时遇到了一些问题。mongoDB代码适用于每种情况,但当我将其包含在单个查询中时,它就不起作用了。任何想法 我得到以下错误:未捕获异常:错误:命令失败,“确定”:0;“errmsg”:没有这样的命令:“0”,代码:59 我认为问题在于您的$或表达式中的输入错误: 请记住gt操作符之前的$。这可能更适合您的情况: MongoDB Enterprise mongos> db.emp.find() { "_id" : ObjectId(

我是MongoDB的新手,在解决这个问题时遇到了一些问题。mongoDB代码适用于每种情况,但当我将其包含在单个查询中时,它就不起作用了。任何想法

我得到以下错误:未捕获异常:错误:命令失败,“确定”:0;“errmsg”:没有这样的命令:“0”,代码:59


我认为问题在于您的
$或
表达式中的输入错误:

请记住
gt
操作符之前的
$

这可能更适合您的情况:

MongoDB Enterprise mongos> db.emp.find()
{ "_id" : ObjectId("608a5dc78c494a06fe633752"), "saalary" : 10 }
{ "_id" : ObjectId("608a5dcb8c494a06fe633753"), "saalary" : 100 }
{ "_id" : ObjectId("608a5dce8c494a06fe633754"), "saalary" : 1000 }
{ "_id" : ObjectId("608a5dd28c494a06fe633755"), "saalary" : 2000 }
{ "_id" : ObjectId("608a5dd68c494a06fe633756"), "saalary" : 4000 }
{ "_id" : ObjectId("608a73718c494a06fe633757"), "saalary" : 5000 }
MongoDB Enterprise mongos> db.emp.aggregate([
{$group:{
_id:{ 
  "$cond":{ if:{$and:[ 
     {"$gt": [ "$saalary", 0 ]} ,
     {"$lt": [ "$saalary", 3800 ]}] },
     then:"below3800",
     else:{ 
         "$cond":{ if:{$and:[ 
                  {"$gt": [ "$saalary", 3800 ]} ,
                  {"$lt": [ "$saalary", 4800 ]}] },
                  then:"between3800-4800",
                  else:"above4800"  
                  }
             }
          }
        }  ,cnt:{$sum:1} 
      } 
     }  
   ])
{ "_id" : "above4800", "cnt" : 1 }
{ "_id" : "between3800-4800", "cnt" : 1 }
{ "_id" : "below3800", "cnt" : 4 }
MongoDB Enterprise mongos>

除了需要为$gt的拼写错误gt之外,如果您想在一个查询中包含两个不同的组,则不能按顺序运行它,您可以使用$facet将任务拆分为两个流,并在…db.employees.aggregate([{facet:{$match:{$or:[{salary:{$gt:0,$lt:38000}}}},{$group:{id:0,“count”:{$sum:1}}})之后将它们重新连接起来,[$match:{$or:[{$salary:{$gt:38000,$lt:48000}]},{$group:{{u id:38000,“count:{$sum:1}}}}])这是使用$faceit功能的正确方法吗
MongoDB Enterprise mongos> db.emp.find()
{ "_id" : ObjectId("608a5dc78c494a06fe633752"), "saalary" : 10 }
{ "_id" : ObjectId("608a5dcb8c494a06fe633753"), "saalary" : 100 }
{ "_id" : ObjectId("608a5dce8c494a06fe633754"), "saalary" : 1000 }
{ "_id" : ObjectId("608a5dd28c494a06fe633755"), "saalary" : 2000 }
{ "_id" : ObjectId("608a5dd68c494a06fe633756"), "saalary" : 4000 }
{ "_id" : ObjectId("608a73718c494a06fe633757"), "saalary" : 5000 }
MongoDB Enterprise mongos> db.emp.aggregate([
{$group:{
_id:{ 
  "$cond":{ if:{$and:[ 
     {"$gt": [ "$saalary", 0 ]} ,
     {"$lt": [ "$saalary", 3800 ]}] },
     then:"below3800",
     else:{ 
         "$cond":{ if:{$and:[ 
                  {"$gt": [ "$saalary", 3800 ]} ,
                  {"$lt": [ "$saalary", 4800 ]}] },
                  then:"between3800-4800",
                  else:"above4800"  
                  }
             }
          }
        }  ,cnt:{$sum:1} 
      } 
     }  
   ])
{ "_id" : "above4800", "cnt" : 1 }
{ "_id" : "between3800-4800", "cnt" : 1 }
{ "_id" : "below3800", "cnt" : 4 }
MongoDB Enterprise mongos>