2016-06-29 2 views
1

이 내가 내가 특정 연도 및 특정 월의와의 레코드 만 원하는mongodb에서 특정 달의 현명한 기록을 얻는 방법?

{ "_id" : { "year" : 2015, "month" : 8, "day" : 15 }, "sum" : 200 } 
{ "_id" : { "year" : 2016, "month" : 5, "day" : 20 }, "sum" : 150 } 
{ "_id" : { "year" : 2016, "month" : 6, "day" : 29 }, "sum" : 250 } 

로 출력을 얻고있다

db.expenses.aggregate([ 
    { 
     $project: { 
      _id: 1, 
      year: { $year: "$createdat" }, 
      month: { $month: "$createdat" }, 
      day: { $dayOfMonth: "$createdat" }, 
      expenseprice: 1 
     } 
    }, 
    { 
     $group: { 
      _id: { 
       year: "$year", 
       month: "$month", 
       day: "$day" 
      }, 
      sum: { $sum: "$expenseprice" } 
     } 
    } 
]) 

이 쿼리를 시도

empname: {type: String}, 
soldby: {type: String}, 
expenseprice:{type:Number}, 
expensedesc:{type:String}, 
expensetype:{type:String}, 
createdat: {type: Date, default: Date.now} 

내 스키마입니다 그 달, 현명한이 일

{ "_id" : { "year" : 2016, "month" : 6, "day" : 28 }, "sum" : 150 } 
{ "_id" : { "year" : 2016, "month" : 6, "day" : 29 }, "sum" : 200 } 

내가 너무

db.expenses.aggregate([ 
    { 
     $project: { 
      _id: 1, 
      year: { $year: "$createdat" }, 
      month: { $month: "$createdat" }, 
      day: { $dayOfMonth: "$createdat" }, 
      expenseprice: 1 
     } 
    }, 
    { 
     $match: { 
      $eq: ["$month", 06] 
     } 
    }, 
    { 
     $group: { 
      _id: { 
       year: "$year", 
       month: "$month", 
       day: "$day" 
      }, 
      sum: { $sum: "$expenseprice" } 
     } 
    } 
]) 

$match을 시도하지만이

assert: command failed: { 
    "ok" : 0, 
    "errmsg" : "bad query: BadValue unknown top level operator: $eq", 
    "code" : 16810 
} : aggregate failed 
[email protected]/mongo/shell/utils.js:23:13 
[email protected]/mongo/shell/assert.js:13:14 
[email protected]/mongo/shell/assert.js:266:5 
[email protected]/mongo/shell/collection.js:1215:5 
@(shell):1:1 

2016-06-29T16:20:47.754+0530 E QUERY [thread1] Error: command failed: { 
    "ok" : 0, 
    "errmsg" : "bad query: BadValue unknown top level operator: $eq", 
    "code" : 16810 
} : aggregate failed : 
[email protected]/mongo/shell/utils.js:23:13 
[email protected]/mongo/shell/assert.js:13:14 
[email protected]/mongo/shell/assert.js:266:5 
[email protected]/mongo/shell/collection.js:1215:5 
@(shell):1:1 

답변

1

$ 그룹의 연도와 월을 참조 할 수있는 방법에 대한 아래의 샘플을 참조하십시오 같은 오류를 얻고있다. 내 이해에 따라, 그것은 당신이 당신의 요구 사항에 필요한 마지막 비트입니다.

db.expenses.aggregate([ 
    {$project: {_id:1,year:{$year:"$createdat"},month:{$month:"$createdat"}, day:{$dayOfMonth:"$createdat"},expenseprice:1}}, 
    {$group: {_id:{year:"$year",month:"$month",day:"$day"}, sum:{$sum:"$expenseprice"}}}, 
    {$match : {"_id.year" : 2016, "_id.month" : 6}}]) 

왜 일치 후에 다른 그룹을 추가했는지 확신 할 수 없습니다. 나의 처음 이해에서, 그것은 요구되지 않을지도 모른다. 위의 해결 방법이 예상과 다를 경우 의견이나 요구 사항을 업데이트하십시오. 그에 따라 대답을 조정할 것입니다.

일부 샘플 데이터로 내 쿼리를 테스트했습니다. 데이터가 한 달 동안 필터링되고 나는 현명한 분석을 얻습니다.

관련 문제